"This" keyword in javascript

时间:2015-06-15 14:44:22

标签: javascript

Will the following code return the same result? I can't really understand this keyword.

var o = {
    prop: 37,
    f: function () {
        return this.prop;
    }
};

console.log(o.f()); // logs 37


var A = {
    prop: 37,
    f: function () {
        return A.prop;
    }
};

console.log(o.f()); // logs 37

2 个答案:

答案 0 :(得分:1)

Yes, those two pieces of code will return the same result.

When a function is called as a method of an object, its this is set to the object the method is called on.

Here, the object invoking it is the same in both the cases.

The documentation on this can be helpful.

答案 1 :(得分:1)

(I'm going to assume you meant to call A.f() in the second part.

Yes, they will return the same result. The second example might make it hard to have two object instances that share the same function, but in many cases that doesn't really matter.

Except for certain "binding", or "hitching" situations that have to be manually set up, this can be determined from the dot before the method call.

iamthis.callmethod()