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
thisrefers correctly to the object returned bybar: