Reputation: 734
This question is already asked and the solution proposed is of using 'bind'. But how to use 'bind' for this case ?
var Fun = function(){
this.count = 100;
}
Fun.prototype.f = function(){
console.log("in f : " + this.count);
}
Fun.prototype.g = {
f : function(){
console.log("in g-f : " + this.count);
// Is it possible to use 'bind' here to access 'this' of 'Fun'
}
}
fun = new Fun();
fun.f(); // Results - in f : 100
fun.g.f(); // Results - in g-f : undefined
fun.g.f.bind(fun)(); // Results - in f : 100
Is it possible to use bind
in g.f
such that fun.g.f()
will give the result in f : 100
?
Upvotes: 1
Views: 75
Reputation: 29946
No, as fun.g
is a different object. All you can do is to put a differnet g
object in all instances of Fun
, and put a bound function f
in there.
function Fun() {
this.count = 100;
this.g = {
f: function() {
console.log("in g-f : " + this.count);
}.bind(this);
};
}
Fun.prototype.f = function() {
console.log("in f : " + this.count);
};
Upvotes: 1
Reputation: 1075587
Is it possible to use 'bind' here to access 'this' of 'Fun'
No, because there's no this
to bind at the point you're creating the second f
. You'd have to do it in Fun
instead:
var Fun = function(){
this.count = 100;
this.g = {
f: function() {
console.log("in g-f : " + this.count);
}.bind(this)
};
};
Or without bind:
var Fun = function(){
var t = this;
this.count = 100;
this.g = {
f: function() {
console.log("in g-f : " + t.count);
}
};
};
This does involve creating a new function for every instance. Modern browser engines will reuse the function's code between instances even though distinct function objects are created.
If you wanted to make the main body of f
used from the prototype, that's also possible: Put g
on the prototype as you've shown, then:
var Fun = function(){
var t = this;
var oldg = this.g;
this.count = 100;
this.g = {
f: function() {
return oldg.f.apply(t, arguments);
}
};
};
Now, if Fun.prototype.g.f
changes after the instance is created, you use the updated version. But if Fun.prototype.g
is replaced with a reference to a new object, it'll break.
Upvotes: 6