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'}!!!!
obj.cool 作为一个引用 传递个setTimeout, setTimeout 调用这个函数的时候是 '函数调用(而不是方法调用)' 所以this指向全局对象
上面的代码this是相当于
真正调用cool方法的是window,this指向调用者,所以打印出来的是window.id
因为这个
this是指向window的怪我知识短浅,我只知道,setTimeout() 和 setInterval() 调用的代码或者函数是全局作用域的
setTimeout是window对象所调用的正所谓
this指向调用它所在函数的那个对象理解了这句话,就理解了
this的指向普通函数的 this 不是定义时的,而是调用时的。
在控制台中运行下面的代码(不好意思哈,写代码不切换输入法,注释是英文的了):
老生常谈的 this 问题了, obj.cool它的本质就是一个函数。