Javascript中this的疑问,函数作为某对象的方法调用,这时this就指这个上级对象。

看到大神在介绍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

阅读 3.9k
5 个回答

全局下this===window

在全局环境下执行console.log()this当然指向window了;
this指向的是函数当前的执行环境

o.m()是隐式绑定this到o对象
全局作用域下this指向全局对象

要记住,另外一种调用方式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 会随着上下文的意义而改变,不是不变的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题