this
call apply bind
function Base(foo) {
this.foo = foo
}
function Child(foo) {
Base.call(this, foo) // 可以理解成继承,不过是把 this 替换成了 Child 的了
}
const child = new Child('foo')相同
区别
应用
const arr = [1, 22, -10, 0, 9] const max = Math.max.apply(Math, arr) console.log(max) // 22 // 利用 ... 运算符也可以 const max = Math.max(...arr)x = 0 // global const foo = { x: 10, // foo getX: function() { return this.x } } console.log(foo.getX()) // 10 const retrieveX = foo.getX console.log(retrieveX()) // 0,函数里的 this 实际指向的是 global // 注意 bind 返回的才是绑定过的对象 const boundGetX = retrieveX.bind(foo) console.log(boundGetX()) // 10, 函数里的 this 重新指向了 foo
this 指向
普通函数中的 this
匿名函数的 this
箭头函数的 this
Last updated