Here is the code
function SuperType(){
this.property = 'aa';
}
SuperType.prototype.property='aaa'
SuperType.prototype.getSuperValue = function(){
console.log("this===s : "+(this===s))
console.log("this===SuperType.prototype : "+(this===SuperType.prototype))
return this.property;
}
var s=new SuperType();
console.log(s.getSuperValue())
My question is why this
in getSuperValue
refer to s
? In a normal sense,it should refer to 'SuperType.prototype'.
At first glance, getSuperValue()
is called by s
,so this
in getSuperValue
scope should refer to s
.
However s.getSuperValue
is actually s.__proto__.getSuperValue()
that is why I think this
in getSuperValue
refer to SuperType.prototype
==========================================
I studied all the answers in How does the "this" keyword work? and failed to find anything explain the question
I real reason is
s.getSuperValue() <=> Object.getPrototypeOf(s).getSuperValue.call(s)
while I wrongly regard it as
s.getSuperValue() <=> Object.getPrototypeOf(s).getSuperValue()
To those who concerns ,just put the answer here
===============================================
Got some new understanding of this issue
even though the function reside in prototype
console.log(s.getSuperValue===s.__proto__.getSuperValue) //true
The lookup process is not related to how this
is bound
console.log(s.getSuperValue()) // 'aa'
console.log(s.__proto__.getSuperValue()) //'aaa'
this
is only determined exclusively by where the function is called
=================== update ================
A more demonstrating example :
function merge(a, b){
if (a && b) {
for (var key in b) {
a[key] = b[key];
}
}
return a;
};
var a={hello:"world"}
var aa={hi:function () {
console.log(this.hello)
}}
var aaa=merge(a,aa)
aaa.hi()