我个人的想法是所有的声明变量都是挂在当前的this上的。但是JavaScript的this是根据运行环境不同而变化的,所以我有有疑惑。
这个能够直接的在全局上得到验证,如下test是全局变量,使用window.test就能拿到这个变量
var test = '111';
(function(){ // this === window
console.log('1',test) // 111
console.log('2',window.test,this.test) // 111 111
})();
复制代码
从上面看好像是这么回事的样子。。。。。。但是
var test = '111';
(function(){ // this === window
console.log('1',test) // 111
console.log('2',window.test,this.test) // 111 111
var name = 'zhangsan'
console.log('3',this.name,window.name) // 显示为空
})();
复制代码
我想验证局部变量的时候,找不到能够正确验证的方式,不知道对与错。
function ttt(){
var test = '222'
this.tt = '333'
console.log('3',this,this.test,this.test) // 3 ttt {tt: "333"} undefined undefined
}
console.log('4',new ttt(),new ttt().__proto__.test)
这个ttt实例的_proto_本质上也不是ttt方法。
复制代码
看样子我的想法是错的,但是我还是不明吧,全局的变量声明,挂在了当前this(window)上,局部变量为什么没有挂上去