关于JavaScript中的this指向

var test ={
  'a':1,
  'b':{
   'b1':function(){
    console.log(this === test);
   }.bind(test)
  }
 }
test.b.b1();

为什么结果为false……

阅读 2.7k
4 个回答

bind时test值为undefined,因此this === test中的this指向了window,所以为false

首先js对象是一定不会相等(==)的,更不要说===。
如果想要判断两个对象的数据完全相等,需要进行深层遍历。

var test = {
    'a': 1,
    c: (function () {
        console.log(test)
    })(),
    'b': {},
}

test.b.b1 = function() {
    console.log(this == test);
}.bind(test)

test.b.b1();

输出结果
undefined
true

var test ={
    'a':1,
    'b':{
        'b1':function(){
            console.log(test);
            console.log('--------------------\r\n');
            console.log(this);
            console.log('--------------------\r\n');
        }.bind(null)
    }
}
test.b.b1();

结果是一样的

var test ={
    'a':1,
    'b':{
        'b1':function(){
            console.log(test);
            console.log('--------------------\r\n');
            console.log(this);
            console.log('--------------------\r\n');
        }.bind(test)
    }
}
test.b.b1();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题