看到大神在介绍this的时候第二个使用环境,原文在此:
http://www.ruanyifeng.com/blo...
这里的对象o应该就是this?如果是的话为什么这样最不全等?
function test(){
console.log(this.x);
}
var o = {};
o.x = 1;
o.m = test;
console.log(o.m());
console.log(o===this);
输出的分别是:
1
false
看到大神在介绍this的时候第二个使用环境,原文在此:
http://www.ruanyifeng.com/blo...
这里的对象o应该就是this?如果是的话为什么这样最不全等?
function test(){
console.log(this.x);
}
var o = {};
o.x = 1;
o.m = test;
console.log(o.m());
console.log(o===this);
输出的分别是:
1
false
要记住,另外一种调用方式func.call(context, x, m) 上面的两种方式只是语法糖 可以通过“转换代码”的方式如:
function test(){
console.log(this.x);
}
等价于
function test(){
console.log(this.x);
}
test.call(undefined)
按理说打印出来的 this 应该就是 undefined 了吧
但是浏览器里有一条规则:
如果你传的 context 就 null 或者 undefined,那么 window 对象就是默认的 context(严格模式下默认 context 是 undefined)
因此上面的this对应的应该是 window。
let o = {
x: 1,
m: function(){
// 这里的 this 是 o 对象
console.log(this.x);
}
}
console.log(o === this); // 这里的 this 是 window
this 会随着上下文的意义而改变,不是不变的
10 回答11.2k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
全局下this===window