为什么这在AngularJS中有效

3

我这里有一段代码片段(可以正常使用),但我不明白为什么在 addReview 函数中我们还能使用 this.review。因为 this 变量必须是用于 addReview 函数而非父函数。如果我错了,请纠正我。

app.controller('ReviewCtrl',function() {
    this.review= {};
    this.addReview = function(product) {
        product.reviews.push(this.review);
        this.review={};
    }
});

3
查看此帖子https://dev59.com/7Ggu5IYBdhLWcg3wEzDP - 个人认为至少在使用$scope的情况下,您可以始终保证其状态。 - GillesC
@gillesc 感谢您的好文章,$scope 会很有用。但我的问题更多地涉及 JavaScript 的基础知识,关于 this 的作用域。在父函数中使用的 this 和在子函数中使用的 this 应该是不同的,这看起来很琐碎。 - hard coder
1个回答

2

这不是Angular,而是JavaScript和继承在发挥作用,这一切都很合理。

如果方法附加到原型上,您会期望this像这里一样正常工作。在构造函数中添加方法具有相同的效果,这就解释了为什么子类中的this与父类相同的原因。

为什么不呢?如果您考虑一下,为什么原型上的方法内部的this应该引用构造函数,因为没有它,面向对象编程将无法正常工作。

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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接