说说对this关键字的理解
# 是什么
this: js运行中的关键字, 指向调用它的对象
一句话: 谁调用this就指向谁
- 特性 严格模式有一些区别
# 怎么用
# 全局函数
指向window
var name = 'fang'
function foo(){
console.log(this.name)
}
foo() // fang
# 对象函数
var name = 'hello'
let obj = {
name: 'fang',
sayName: function(){
console.log(this.name)
}
}
obj.sayName() // fang
# 箭头函数
指向定义箭头函数外层this
var name = 'hello'
let obj = {
name: 'fang',
sayName: () => {
console.log(this.name)
}
}
obj.sayName() // hello
# call/apply
执行第一个参数
let name = 'hello'
function foo(){
console.log(this.name)
}
foo.call({name: 'fang'}) // fang
# 构造函数
指向实例
function Foo(name){
this.name = name
}
let f1 = new Foo('f1')
f1.name // f1
# 事件
指向点击元素
var button = document.querySelector('button');
button.onclick = function(e){
console.log(this === e.currentTarget); // true
}
上次更新: 2021/12/19, 18:05:42