3

I have following code snippet(working) here, why can we still use this.review inside addReview function. It seems wrong context for using this.review because this variable must be for addReview function not for parent function. Correct me if I am wrong.

app.controller('ReviewCtrl',function() {
    this.review= {};
    this.addReview = function(product) {
        product.reviews.push(this.review);
        this.review={};
    }
});
hard coder
  • 5,449
  • 6
  • 36
  • 61
  • 3
    See this post http://stackoverflow.com/questions/11605917/this-vs-scope-in-angularjs-controllers - personally I would use `$scope` instead at least you are guaranteed on its state at all time. – GillesC Jul 16 '14 at 08:39
  • @gillesc Thanks for this good post and $scope will do good. But my question is more on fundamentals of javascript, about the scope of `this`. It looks trivial that `this` used in parent function and `this` used in child function should be different. – hard coder Jul 16 '14 at 08:53

1 Answers1

2

It's not angular, it's javascript and inheritance at play and it all make perfect sense.

If the method was attach to the prototype you would expect this to work like it does here. Adding a method in the constructor has the same effect which explains why this in the child is the same this.

Why wouldn't it? If you think about it why should this inside method on the prototype refer to the constructor to, because OOP wouldn't work well without it.

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();
GillesC
  • 10,647
  • 3
  • 40
  • 55