0
我有一个简单的原型继承构造函数,我正在使用箭头函数。JavaScript:在ES6中使用`this`与原型和箭头函数
app.Node = function (name, type) {
this.name = name;
this.type = type;
this.children = [];
}
app.Node.prototype = {
addChild: (child)=>{
child._parent = this;
this.children.push(child);
},
removeChild: (child)=>{
this.children.forEach((item, i) => {
if (item === child) {
this.removeChildAtIndex(i);
}
});
},
}
然而,由于this
和箭头功能性质,this
值为undefined
上面的原型的方法之内。那么我能以这种方式使用箭头功能吗?我不知道我需要改变什么,除了使用正常的function
函数。
你很好地掌握了箭头和普通函数的区别。箭头功能不仅仅是捷径。在你的特定情况下,可以使用方法的快捷方式,https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer#Method_definitions – estus