user1822824
user1822824

Reputation: 2488

JavaScript Function Format: Is one of these a method?

What's the difference between:

pause: function () {
    this.state.gamePaused = true;
},

and

function pause() {
    this.state.gamePaused = true;
}

Upvotes: 2

Views: 221

Answers (4)

Aesthete
Aesthete

Reputation: 18848

  1. Attached to an object, this is still a function, but called a method. It is attached to the object and it's this parameter refers to that object. Call it like so: obj.pause()

  2. Defined in the global namespace, this function can be called from anywhere, and is attached to the window object. this refers to the window object whilst in the function. Call it simply like so: pause()

Note that both functions are really methods, although the latter is rarely referred to as one.

Upvotes: 1

I Hate Lazy
I Hate Lazy

Reputation: 48761

ECMAScript defines a method as a function that is the value of a property. So when you put a function on an object, we refer to it as that object's method.

So to answer the question, the first one is a method.

ECMAScript 4.3.27 - method

function that is the value of a property.

NOTE When a function is called as a method of an object, the object is passed to the function as its this value.

Upvotes: 2

Benjamin Cox
Benjamin Cox

Reputation: 6120

Both are functions (aka methods), it's just that they are declared in two different ways for use in two different settings.

In JS you can define objects like so:

var obj = {
    flagVariable:  false,
    intVariable:    115,
    stringVariable:  'hello world',
    functionVariable:  function() { alert("Hello world!"); }
}

In this example, the last property of the object is a function. This is an anonymous function, meaning it is not, itself, named. That's why there's no name between the 'function' and the '()'. So you reference it using the variable you assigned it to, like so:

foo.functionVariable();

You can also pass it around and execute it by the name of whatever variable you assign it to:

var callback = foo.functionVariable;
callback();

You can also declare functions just about anywhere, so in the global scope you can say:

function pause () {  alert("Hello world!"); }

This defines a named function, which can be executed from anywhere by name:

pause(); 

Incidentally, this, too, can be passed around:

var callback = pause;
callback();

Upvotes: 3

Ivan
Ivan

Reputation: 10372

The first example is probably part of an object, which means that pause is a function of an Javascript object and the second one pause as a stand alone function.

I'd expect to see the first example in something like:

var someObject = {
  pause: function () {
    this.state.gamePaused = true;
  },
  anotherProperty : "some value"
}

And thus it is used like:

someObject.pause();

On the other hand, the second example would be used like:

pause();

Upvotes: 3

Related Questions