问一个比较简单的js原生题目

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

</body>
    <script type="text/javascript">
        var obj = {
            id:"aw",
            cool:function coolFn(){
                console.log(this.id);
            }
        }
        var id = 'not  aw';
        setTimeout(obj.cool,100);
    </script>
</html>

为什么加了settimeout以后输出的是全局变量的id

阅读 3.8k
8 个回答

obj.cool 作为一个引用 传递个setTimeout, setTimeout 调用这个函数的时候是 '函数调用(而不是方法调用)' 所以this指向全局对象

var obj = {
    id:"aw",
    cool:function coolFn(){
        console.log(this.id);
    }
}
var id = 'not  aw';
setTimeout(obj.cool,100);

上面的代码this是相当于

var obj = {
    id:"aw",
    cool:function coolFn(){
        console.log(this.id);
    }
}
var id = 'not  aw';
var func = obj.cool;
setTimeout(func ,100);

真正调用cool方法的是window,this指向调用者,所以打印出来的是window.id

因为这个this是指向window

怪我知识短浅,我只知道,setTimeout() 和 setInterval() 调用的代码或者函数是全局作用域的

setTimeoutwindow对象所调用的

正所谓this指向调用它所在函数的那个对象

理解了这句话,就理解了this的指向

普通函数的 this 不是定义时的,而是调用时的。

在控制台中运行下面的代码(不好意思哈,写代码不切换输入法,注释是英文的了):

function a0 () {
  console.log(this.x)
}

function a1 () {
  this.x = 'x'
  console.log(this.x)
}
a0() // global call, `this` is `window`, this.x is `undefined`
a1() // global call, `this` is `window`, this.x is 'x', and now `window` has a property x with value 'x'

var b = {x: 'y'}
a0.call(b) // `this` is `b`, prints: 'y', `b` is {x: 'y'}
a1.call(b) // `this` is `b`, prints: 'x', now `b` is {x: 'x'}!!!!

老生常谈的 this 问题了, obj.cool它的本质就是一个函数。

setTimeout(obj.cool,100); 《==》 setTimeout(function coolFn(){console.log(this.id))},100)
var obj = {
            id:"aw",
            cool:function coolFn(){
                console.log(this.id);
            }
        }
        var id = 'not  aw';
        setTimeout(obj.cool.bind(obj),100);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题