What does "this" mean in JavaScript Parasitic Inheritance?

After years of creating applications using prototype inheritance in JavaScript, I began to study the use of spurious inheritance. Despite my basic mistake - at least for me - potentially creating multiple copies of methods in memory, when you create a hierarchy of objects, I find that it really resonates with me with its simplicity and the fact that the β€œnew” turns out to be unnecessary. However, I am stuck with what is happening with β€œthis.” Most of the examples that I saw on the Internet only scratch the surface, demonstrating how to implement spurious inheritance like this:

function foo() { return { method1 : function() {...} } } function bar() { var that = foo(); that.method2 = function() { //is "this" pointing to bar()? } return that; } 

As I asked in a comment on a bar () object, does "this" have a reference to bar (), or is the scope of this rejected by method2?

Thanks!

+7
source share
2 answers

A quick test shows that this correctly refers to the object returned by bar :

 function foo() { return { method1 : function() { return "spam" } } } function bar() { var that = foo(); that.method2 = function() { return this.method1(); } return that; } var b = bar(); b.method2(); // "spam" 
+3
source

this context variable this context variable will be bound to the object that is returned from the foo() function of the pseudo constructor. Each function (context) has this associated with this , the value from the context variable depends on the call from the method itself.

For example, calling a function as a property from an object (for example, you are there) will set this variable to this object. When you simply call a function immediately, its this bound to the global object in ES3 and its null in ES5.

There are other methods and keywords that can change the meaning of this . Like new , .bind() , .call() and .apply() . But then again, in your specific fragment here, this will be bound to the object that is stored in that .

+1
source

All Articles