<script type="text/javascript">
function zdw(){
var name="asasas";
function showname(){
console.log(this);//window
console.log(this.name);
}
this.show=function(){
showname();
console.log(this);//zdw
}
}
// zdw.prototype.setname=function(str){
// name=str;
// } //为什么这里name就变成在window下了
var zzddww=new zdw();
// zzddww.setname("22222");
zzddww.show();
</script>
1:为什么showname()的this指向window
2:为什么
zdw.prototype.setname=function(str){
name=str;
}
这个后name就是放在了window下
this
在JavaScript语言精粹里面有讲到,在chapter 4 - Function, Invocation。里面讲了4种pattern。题中属于其中2种,function invocation pattern 和constructor invocation pattern
下面是原理,详细的翻译文章看楼上介绍那篇。
ECMAScript 3rd:
this
的值取决于你怎么调用他。原理就是是由reference type所决定的。reference type即是
()
左边的identifier。identifier有function name, variable name, object property。比如题中的showName()
。reference type又是由他自己的base object所决定的。即,看identifier是属于哪个base object。
也就是说,
this
的值取决于reference type的base object。根据上面,当调用
showName()
的时候,在()
左边的identifier是showName
, 而showName
是属于他所在的anynomous function的active object里。也就是base object是active object,在ECMAScript 3里面,此时this的值是global object
,但ECMAScript 5中已经fixed, 为undefined
。而
zzddww.show()
的时候,在()
左边的是identifier是show
,而show
的base object是zzddww
这个object,所以this就是zzddww
。