Igor Parra
Igor Parra

Reputation: 10348

Confusion about this, global object and global scope

Reading Doug's "Javascript: the goods parts" in the chapter 4 about functions talk about "The method invocation pattern" and "The function invocation pattern" (page 28).

When a function is stored as a property of an object, we call it a method. When a method is invoked, this is bound to that object.

That is clear. Then in the same page:

When a function is not the property of an object, then it is invoked as a function:
var sum = add(3, 4); // sum is 7
When a function is invoked with this pattern, this is bound to the global object. This was a mistake in the design of the language.

My questions:

Thanks.-

EDIT: Both answers given are very instructive and well documented. Thanks to all participants.

Upvotes: 2

Views: 444

Answers (2)

rosscj2533
rosscj2533

Reputation: 9323

1 - Yes

2 - If you keep reading, right after that he describes an example that makes it a 'mistake in the design of the language'.

var myObject = {
  value: 1
};

myObject.double = function() {
  var that = this;

  var helper = function() {
    alert('in helper, this.value = ' + this.value + ' and that.value = ' + that.value);
    that.value = that.value + that.value;
  }

  helper();
};

myObject.double();
alert('after doubling, myObject.value = ' + myObject.value);

The alert will show that using 'this' in the function that is a property of the object will not work. If the global object (likely window) had a .value, then that would be seen in that alert.

Upvotes: 1

Will
Will

Reputation: 20225

window is the global object in JavaScript. If you define a function like this:

function myFunc() {
}

It will be bound to the global object, window and using this inside the function will refer to the window object. If you define a function as a property of an object, such as:

var obj = {
   myMethod: function() {
   }
};

And use this, it will refer to the object.

Here is an example: http://jsfiddle.net/williamvanr/qBXF8/

Upvotes: 1

Related Questions