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={};
    }
});
2
  • 3
    See this post stackoverflow.com/questions/11605917/… - personally I would use $scope instead at least you are guaranteed on its state at all time. Commented Jul 16, 2014 at 8: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. Commented Jul 16, 2014 at 8:53

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.