Reputation: 6609
lets say I have
function cookie(a, b) {
this.a = a;
this.b = b;
this.sayA = function() {
alert(this.a);
}.bind(this);
}
cookie.prototype.sayB = function() {
alert(this.b);
}
var nc = new cookie(1, 2);
addEventListener("load", nc.sayA);
addEventListener("load", nc.sayB);
So, sayA finds the context I want since its bound to the object that holds it, sayB has no clue whats up though. How would I bind "this" to a function that I define in the object prototype?
Upvotes: 0
Views: 58
Reputation: 55759
You almost certainly don't want to do this:
function cookie(a, b) {
this.a = a;
this.b = b;
Object.getPrototypeOf(this).sayB = sayB.bind(this);
}
function sayB() {
alert(this.b);
}
var c1 = new cookie(null, 'from c1');
var c2 = new cookie(null, 'from c2');
c1.sayB(); // "from c2"
c2.sayB(); // "from c2" (i.e. both from c2)
Each cookie created overwrites the function on the prototype chain, which is not what you wanted (probably).
Upvotes: 0
Reputation: 944015
You can't.
When you define the function, the object you want to bind it to doesn't exist.
When you call the function, it has already been detached from the function and passed as an argument.
You can either:
Upvotes: 0
Reputation: 1460
2 options here
function cookie(a, b) {
this.a = a;
this.b = b;
this.sayA = function() {
alert(this.a);
}.bind(this);
}
cookie.prototype.sayB = function() {
alert(this.b);
}
var nc = new cookie(1, 2);
addEventListener("load", nc.sayA);
addEventListener("load", nc.sayB.bind(nc));
addEventListener("load", () => nc.sayB() );
Upvotes: 1