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.

FutureCake
  • 2,108
  • 16
  • 43

2 Answers2

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));
Jurij Jazdanov
  • 1,150
  • 6
  • 10
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();
Cerbrus
  • 60,471
  • 15
  • 115
  • 132