N
N
Nikolay Marinkin2015-05-01 14:22:41
JavaScript
Nikolay Marinkin, 2015-05-01 14:22:41

How to set a variable for all child functions of a JS object?

I am developing a web application in which I actively use object prototypes.
For convenience, I would like to have a short name for accessing the object. This name could be this , but considering that in prototype functions I may have other functions where the scope will change - this option is not suitable.
Setting a variable and assigning this to it is also not an option, these are extra lines of code.

var myClass = function () {}

myClass.prototype {
  foo: function () {
    //тут this это myClass
    var myClass = this;

    function bar () {
      //тут this это НЕ myClass, к нему можно обратиться только через переменную myClass
    }
  }
}

Is it possible to set a variable to all child functions of an object at once?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Shatokhin, 2015-05-01
@NicoBurno

myClass.prototype {
  foo: function () {
    var bar = function () {
     // теперь this работает
    }.bind(this);
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question