Skip to content Skip to sidebar Skip to footer

Why Is There No Implicit This In Javascript

In JavaScript, this must always be stated explicitly when accessing its properties. For example: function Frobber(x) { this.x = x; return this; } Frobber.prototype.frob =

Solution 1:

You have to explicitly specify "this" because "window" is implicit instead

Code

functionSomeFunc(x) {
    y = x;
    returnthis;
}

Is the same as

functionSomeFunc(x) {
    window.y = x;
    returnthis;
}

Solution 2:

What "this" refers to in Javascript is wholly a function of how the current function has been called.

If it is called as a method (i.e. with the . operator) then 'this' will be set to the object before the dot.

If it is called as a simple function, then 'this' will be the global object (usually the window).

IIRC if you use Function.call, you can set it explicitly.

Javascript is an OO language but does not have classes, and does not (strictly) have methods.

Solution 3:

Each function object introduces a new namespace and populates it with its parameters, variables and inner function declarations. If all the properties of the this object were to be injected into this same namespace, the names would collide.

To prevent this collision, you would have to explicitly make sure that each parameter name, local variable name or function declaration name is not the same as any of the properties of the object that is referenced by this.

Since you can dynamically add new properties to an object, you would also have to make sure that any new property that you add, does not collide with all those parameters, variables,... in each of the objects methods.

This would be nearly impossible to deal with.

Solution 4:

If x is implied to be this.x, how would you access variables defined as the name x?

functionFrobber(x) { this.x = x; }
Frobber.prototype.frob = function() {
   var x = 'WHAT ABOUT ME';
   return x;
}

Solution 5:

From JavaScript: The Good Parts (Functions -- Invocation):

There are four patterns of invocation in JavaScript: the method invocation pattern, the function invocation pattern, the constructor invocation pattern, and the apply invocation pattern.

Basically, each of these "patterns" determine how the this reference is defined. If a function is defined as a method of an object, this will refer to the parent object. If the function is not a property of an object, this refers to the global object. If the function is invoked with the new keyword (i.e. as a constructor) then this refers to the newly created object. And finally, if you use the function's apply() method the reference of this is bound to whatever object you specify.

Post a Comment for "Why Is There No Implicit This In Javascript"