user81993
user81993

Reputation: 6609

how do you bind this when defining a prototype function?

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

Answers (3)

Ben Aston
Ben Aston

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

Quentin
Quentin

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:

  1. Bind it in the constructor
  2. Bind it when you pass it

Upvotes: 0

skav
skav

Reputation: 1460

2 options here

  1. explicitly bind to the instance
  2. just call the member function

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

Related Questions