javascript - How to make "this" keyword refer to current instance, if used from a nested object's method? -


in javascript, if attach function object's prototype, within function, this refers current instance of object. example:

function ragefest(inquiry) {     this.inquiry = inquiry; }  ragefest.prototype.myfunction0 = function () {     console.log(this.inquiry); };  new ragefest("you mad, bro?").myfunction0(); // prints "you mad, bro?" 

running in node prints you mad, bro? terminal, expected.

now, here's run trouble: suppose want introduce second level of organization (maybe because ragefest has lots of methods attached it, , want organize them).

ragefest.prototype.myobject = {     myfunction1: function () { console.log(this.inquiry); },     myfunction2: function () { console.log(this.inquiry); }.bind(this),     myfunction3: function () { console.log(this.inquiry); }.bind(ragefest) };  var ragefest = new ragefest("you mad, bro?");  ragefest.myobject.myfunction1(); // undefined ragefest.myobject.myfunction2(); // undefined ragefest.myobject.myfunction3(); // undefined 

none of these work! if make myobject's 3 functions log this (rather this.inquiry), shows that:

  • myfunction1: this refers myobject
  • myfunction2: this refers global object
  • myfunction3: this refers ragefest constructor

however, binding instance (rather constructor) works:

ragefest.prototype.myobject.myfunction4 = function () {     console.log(this.inquiry); }.bind(ragefest);  ragefest.myobject.myfunction4(); // prints "you mad, bro?" 

this prints out you mad, bro?, desired, feels terrible hack. requires me create instance of ragefest beforehand, annoying.

so, question is, there way of achieving effect want -- functions inside nested object have access current instance using this keyword -- without resorting hackery?

instead of creating nested object creating getter helpful, called in constructor function , assigned object property.

function ragefest(inquiry) {     this.inquiry = inquiry;     this.myobject = this.getmyobject(); }  ragefest.prototype.myfunction0 = function () {     console.log(this.inquiry); };  ragefest.prototype.getmyobject = function(){     var = this;     return {       myfunction1: function () { console.log(that.inquiry); },       myfunction2: function () { console.log(that.inquiry); }      } };  var ragefest = new ragefest("you mad, bro?"); ragefest.myobject.myfunction1(); ragefest.myobject.myfunction2(); 

Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -