I’m trying to make a class without prototypes. Here is an example:
test = (function() {
this.value = 1;
this.print = function() {
console.log(this.value);
};
return this;
})();
This works perfectly as intended. What I don’t understand is this.value inside the this.print function. How does this.print correctly know that any mention of this refers to test and not window? Would any function defined via this.___ = function(){} automatically have this added as a context?
thisalways1 evaluates to the object upon which the function-object was invoked. It will evaluate towindowif it was “invoked upon nothing” (or is a property ofwindow).(Note that
thisis not a variable and is thus not closed-over in a closure! This is why sometimes closures are needed to get the “correct”thiswhich is often known by the variableselforthator_this.)For example:
An example of using a variable to create a binding to the current (as of when the enclosing function was invoked)
this:1 This is a little lie. The
Function.callandFunction.applyfunctions allow specifying thethiscontext and can be used by “context binding” functions such asFunction.bindto eliminate the need for an explicit “self closure” as shown above.