0

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?

user81993
  • 6,167
  • 6
  • 32
  • 64
  • As several objects can have the same prototype, your question logically doesn't work out (which one should it be?!). Setting `this` to the prototype itself should be easy. However, i think you should rather create the bound function when using it, e.g. in the `addEventListener` call, instead of on the object. – ASDFGerte Nov 14 '16 at 16:07

3 Answers3

1

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() );
skav
  • 1,400
  • 10
  • 16
0

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
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

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).

Ben Aston
  • 53,718
  • 65
  • 205
  • 331