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!
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"
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With