全局环境中输出this、指向谁?

全局环境下指向全局对象

console.log(this) // Window {window: Window, self: Window, document: document, name: '', location: Location, …}

全局函数中输出this、指向谁?

全局函数中的this,指向全局对象

内部函数中的this,指向全局对象

function fun(){
    console.log(this)
}

fun() // Window {window: Window, self: Window, document: document, name: '', location: Location, …}

"use strict"; 


fun() // undefined

对象的方法输出this、指向谁?

方法中的this,指向调用方法的对象

let obj = {
    name: 'John',
    getName: function () {
        console.log( this.name );
    }
}
obj.getName() // John

DOM事件输出this、指向谁?

事件中的this,指向触发事件的DOM对象

<button>按钮</button>

const btn = document.querySelector( "button" );
btn.onclick = function () {
    console.log( this ); // <button>按钮</button>
}

构造函数中的this,指向谁?

构造函数中的this,指向new创建的对象

箭头函数中的this,指向定义函数上下文的this

function FUN() {
    this.name = "John";
}
const f = new FUN();

console.log( f ); // FUN {name: 'John'}

总结

  1. 全局环境下指向全局对象
  2. 全局函数中的this,指向全局对象
  3. 内部函数中的this,指向全局对象
  4. 方法中的this,指向调用方法的对象
  5. 事件中的this,指向触发事件的DOM对象
  6. 构造函数中的this,指向new创建的对象
  7. 箭头函数中的this,指向定义函数上下文的this
文章作者: 小森森
版权声明: 本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 小森森博客
源码 JavaScript
喜欢就支持一下吧
打赏
微信 微信
支付宝 支付宝