我在 NodeJS 4 中有一个 ES6 类。 在构造函数中,我想修改一个对象的原型(prototype),以便它现在使用这个类实例来执行操作。
但是,当然,在原型(prototype)范围内,this
不引用我正在创建的类的实例。
class Generic {
constructor() {
this.myClass = util._extend({}, aClass); //shallow copy
this.myClass.prototype.run = function(fn) {
var str = this.toString;
//in the next line, _this_ should refer to the Generic instance.
this.run(str, fn);
};
}
do() {
return this.myClass;
}
run(str, fn) {
...
}
如何引用在 myClass 原型(prototype)范围上创建的通用类实例?
最佳答案
一些选项:
绑定(bind)
:this.myClass.prototype.run = (function(fn) { // `this` is the Generic instance. }).bind(this);
那个
:var that = this; this.myClass.prototype.run = function(fn) { // `that` is the Generic instance. };
箭头函数:
this.myClass.prototype.run = fn => { // `this` is the Generic instance. };
关于javascript - ES 6 类 : Access "this" in another scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33334488/