1

When I run the following code, this returns [object Object] and then returns [object Window]. I understand that this refers to the owner of the function. I understand that window is the owner of the function in the latter case. But who is the owner of the function in the former case? In that case, who is [object Object]?

function Customer(name) {
    this.name = name;
    alert(this);
}

var x = new Customer('John');
Customer('Smith');
darkred
  • 561
  • 4
  • 26
Sandy
  • 787
  • 1
  • 8
  • 20
  • "*'this' refers to the owner of the function*". No, it doesn't. *this* is set by how a function is called, the use of *bind*, or lexically for *arrow* functions. – RobG Jan 02 '16 at 22:02

4 Answers4

1

this, in the former case, is the newly created object instance that will later be assigned to x.

huysentruitw
  • 25,048
  • 8
  • 76
  • 120
1

When you use new Constructor(arguments…), an instance of Constructor is created (a new object inheriting Constructor.prototype), and then Constructor is called with this set to that new instance. That’s just what the new operator does, like this:

var x = Object.create(Customer.prototype);
Customer.call(x, 'Smith');

Note that the global object (window) is the default when you directly call a function that isn’t a property of something; it doesn’t have to do with it being global, for example.

Ry-
  • 199,309
  • 51
  • 404
  • 420
1

"This" is how a function refers to itself. So the name variable is passed into the function but then a different variable, this.name, is set within the function "Customer." The name that belongs to customer is referred to as this.name.

Dave Kanter
  • 940
  • 16
  • 28
0

this is a reference to an object

When you call a function with the new keyword or add a function to an object it assigns the reference to that object to this. In the case of the new keyword the function also returns the reference to the object, which is the same as this

function Test(name){
    this.myName = name;
}

var t = new Test("Obj1");
console.log(t.myName );  // Obj1
Test("Obj2");  // no reference is created and the this keyword stays as is.
console.log(this.myName ); // Obj2
// which is the same as 
console.log(window.myName ); // Obj2
Blindman67
  • 41,565
  • 7
  • 47
  • 102