javascript - 为什么这在 Angular js 中有效

标签 javascript angularjs

我这里有以下代码片段(有效),为什么我们仍然可以在 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/

相关文章:

javascript - 在 NodeJS 中,带有 Promise 的数据库结果未正确返回

javascript - 无法在移动设备上单击 h1

javascript - 将我的 Angular 代码转换为 TypeScript

javascript - Magento - Lightbox 年龄验证脚本 - 两个元素未被 lightbox 隐藏

javascript - 将 ngModel 传递给 AngularJS 组件

javascript - vue-style-loader 来自 cdn 的内联 css

javascript - 如何禁用 saveRow 事件 ui-grid

java - 为什么 '/test' 变为 'localhost:8080/test' 而不是 'localhost:8080/rootcontext/test'

javascript - 如何在 ng-repeat 中按键分配对象数组?

javascript - 无法从指令中选择 ngClass 元素