我这里有以下代码片段(有效),为什么我们仍然可以在 addReview
函数中使用 this.review。使用 this.review
似乎是错误的上下文,因为 this
变量必须用于 addReview
函数而不是父函数。如果我错了,请纠正我。
app.controller('ReviewCtrl',function() {
this.review= {};
this.addReview = function(product) {
product.reviews.push(this.review);
this.review={};
}
});
最佳答案
它不是 Angular ,它是 javascript 和继承在起作用,这一切都非常有意义。
如果该方法附加到原型(prototype),您会期望 this
像这里一样工作。在构造函数中添加一个方法具有相同的效果,这解释了为什么子项中的 this
是相同的 this
。
为什么不呢?如果您考虑一下为什么原型(prototype)上的 this
内部方法应该引用构造函数,因为没有它 OOP 将无法正常工作。
function Parent() {
this.foo = true;
// this works the same way
this.childOnContructor = function() {
console.log(this.foo);
};
}
// this you expect to work
Parent.prototype.childOnPrototype = function() {
console.log(this.foo);
}
var parent = new Parent();
parent.childOnContructor();
parent.childOnPrototype();
关于javascript - 为什么这在 Angular js 中有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24775877/