0

I have a question i have always written functions in javascript for returning or setting values of other elements like so:

function test(x, y){
   return x*y;
}

and call the function like so:

test(20, 50);

but in libraries like jquery you also see functions like so:

var test = something.test();

so my question is what is the difference between the following functions .test() or test() or are they the same and how is this other way of writing a function called?

and how do you write a .function()

Hope to learn something new, sorry if this is a bit random but i am just very curious.

6
  • Surely a something.test() function is just a function called on the object something ? Commented Sep 28, 2017 at 13:41
  • It's just a function that was assigned to an object property. This is called a "method". Commented Sep 28, 2017 at 13:43
  • 1
    @MuthuKumaran Don't we have a JS-specific one that also details how this works? Commented Sep 28, 2017 at 13:44
  • @Bergi: What do you think about the one I added? Commented Sep 28, 2017 at 13:45
  • @Cerbrus Looks good Commented Sep 28, 2017 at 13:48

2 Answers 2

2

This is a function. It is called as function()

function test(a, b) {
  return a * b;
}

console.log(test(2,3));

This is a method of an object. It is a function that is declared in the object and is called as object.function()

var myObject = {
  test: function (a, b) {
    return a * b;
  }
}

console.log(myObject.test(2,3));

Sign up to request clarification or add additional context in comments.

Comments

1

In your example, something.test is a property of something, that happens to be a function.

test(), on the other hand, is just a function, accessible in your current scope.

Here's a extremely simplified example:

const someObj = {
  test: function(){
     console.log('foo!');
  }
}

function test(){
   console.log('bar!');
}

someObj.test();
test();

4 Comments

oke so how would this look in code? how is jquery do do things like: $('element').value() how does this look in code?
thanks for the explaination! i will accept your answer!
You don't really have accept this answer. A better, more complete answer can be found in the linked duplicate targets.
@FutureCake: The $ function simply returns an object with an attribute value (among many others) that is a function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.