Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "this" refer to in JavaScript Parasitic Inheritance?

Tags:

javascript

After years of creating applications using prototypal inheritance in JavaScript, I've started to explore using parasitic inheritance. Despite its primary pitfall - at least to me - of potentially creating several copies of methods in memory as you create an object hierarchy, I'm finding that it really resonates with me with its simplicity and the fact that "new" is rendered unnecessary. However, I'm stuck on what happens with "this." Most of the examples I've seen online only scratch the surface showing how to implement parasitic inheritance like so:

   function foo() {
       return {
          method1 : function() {...}
       }
   }

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

As I asked in the comment in the bar() object, does "this" refer to bar() or is the scope of this relegated to method2?

Thanks!

like image 440
Brendan Delumpa Avatar asked Oct 10 '11 22:10

Brendan Delumpa


2 Answers

The quick test indicates that this refers correctly 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"
like image 91
nrabinowitz Avatar answered Oct 28 '22 20:10

nrabinowitz


The this context variable in your method2() will be bound to the object, which gets returned from foo() pseudo constructor function. Every function (context) has a bound this, the value from the context variable, depends on the invocation from the method itself.

For instance, calling a function as property from an object (like you do there) will set the this variable to exactly that object. When you just call a function right away, its this is bound to the global object in ES3 and its null in ES5.

There are other methods and keywords which can change the value from this. Like new, .bind(), .call() and .apply(). But again, in your particular snippet here, this will be bound to the object which is stored in that.

like image 23
jAndy Avatar answered Oct 28 '22 20:10

jAndy