Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this keyword is window object within a constructor function

Ok, so I thought I understood this (no pun intended), but apparently not.

var Constructor = function () {
    var internalFunction = function () {
        return this === window;
    };
    this.myMethod = function () {
        alert(internalFunction());
    };
};
var myObj = new Constructor();
myObj.myMethod();

This alerts true. Why can't the internal function see this as the object? Instead I have to use alert(internalFunction.call(this)); in myMethod.

Edit: I was looking for an explanation as to why this is assigned in that way, not workarounds such as var self = this;, etc. Sorry if I didn't make that clear.

like image 524
Nathan MacInnes Avatar asked Nov 02 '11 14:11

Nathan MacInnes


People also ask

What is the object in constructor?

Object() constructor The Object constructor turns the input into an object. Its behavior depends on the input's type. If the value is null or undefined , it creates and returns an empty object. Otherwise, it returns an object of a Type that corresponds to the given value.

What is this in constructor function?

About this In a constructor function this does not have a value. It is a substitute for the new object. The value of this will become the new object when a new object is created.

What is constructor keyword?

What is a Constructor in JavaScript? A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword.

What is the this keyword in JavaScript?

In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object. Alone, this refers to the global object.


1 Answers

this is not bound until the function is called and is dependent on how the function is called. You could think of it as an extra parameter implicitly passed to the function.

In this case, the problem is that you're calling internalFunction using internalFunction(). The this value is set either by calling a function as a method (as in foo.bar() or foo["bar"]()) or by setting this explictly via call() or apply(). Your call is doing neither so this reverts to the global object.

The simplest way to achieve what you want in this case while keeping internalFunction private is to store a reference to this inside the constructor function:

var Constructor = function() {
    var thisObj = this;

    var internalFunction = function () {
        return thisObj === window;
    };

    thisObj.myMethod = function () {
        alert(internalFunction());
    };
}
like image 136
Tim Down Avatar answered Sep 28 '22 01:09

Tim Down