0

Say we have this old-school JavaScript:

let obj = {
  foo: function(){
      // this === obj
  },
  bar: function(){
       // this === obj
  }
}

but if we want to attach some properties to foo and bar, like so:

obj.foo.x = function(){
     // this !== obj
}

obj.bar.y = function(){
     // this !== obj
}

what is the most performant pattern to use, to bind the "this" value within obj.foo.x and obj.bar.y to obj?

Sometimes we can reference obj directly instead of using this. However, if obj is the prototype of another object, then referencing obj directly will not yield the correct result. I need to use the this value here (I think).

In other words, this will not work:

obj.foo.x = function(){

}.bind(obj);

obj.bar.y = function(){

}.bind(obj);
  • [`Function.prototype.bind()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) – str Jun 22 '17 at 07:45
  • @str how can I use that here –  Jun 22 '17 at 07:45
  • Possible duplicate of [Use of the JavaScript 'bind' method](https://stackoverflow.com/questions/2236747/use-of-the-javascript-bind-method) – str Jun 22 '17 at 07:45
  • I linked the documentation, I suggest to read it. – str Jun 22 '17 at 07:46
  • I have beening using JS for like 3 years, I know Function.prototype.bind :) I am not sure how to use it here. If it's obvious, then please add an answer, and I will upvote. –  Jun 22 '17 at 07:48
  • @str I updated the question, to demonstrate why Function.prototype.bind is not an obvious solution here. –  Jun 22 '17 at 07:51
  • Then I don't get your question. The code you added which "is not an obvious solution" adds the functions `x` to `obj.foo` and `y` to `obj.bar`. And both functions have `this` bound to `obj`. This is exactly what I thought is what is what you want. – str Jun 22 '17 at 07:57
  • To be very precise - obj will be used as the prototype of another object, bar. I cannot bind obj.foo.x to obj...it needs to be bound to bar. But I do not have a reference to bar when obj is created. See it? –  Jun 25 '17 at 09:11

1 Answers1

0

just use return this;

    let obj = {
  foo: function(){
      // this === obj
  },
  x: function(){
      // this === obj
  },
  bar: function(){
       // this === obj
    return this;
  }
}

than you can call obj.bar().x();

  • I don't want x to be a direct property of obj, I need x to be a "secondary" property of obj. –  Jun 22 '17 at 07:49