Table of Contents
bind this
- 隐式绑定
调用对象下面的方法,自动绑定这个对象,如果没有,则为 undefined
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| function hello() { console.log(this) }
hello()
const foo = { name: 'foo', hello: function() { console.log(this.name) } }
foo.hello()
|
- 显式绑定(call,apply,bind)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const foo = { name: 'foo', hello: function() { console.log(this.name) } }
const bar = { name: 'bar' }
foo.hello.call(bar) foo.hello.apply(bar) const newFn = foo.hello.bind(bar) newFn()
|
- new 绑定
1 2 3 4
| function Test() { this.foo = 1 } new Test()
|
- 箭头函数
箭头函数中的 this
是父作用域中的 this
call
1 2 3 4 5 6 7 8 9 10 11
| Function.prototype._call = function(context = window, ...args) { const key = Symbol() context[key] = this const result = context[key](...args) delete context[key] return result }
|
apply
与 call
相同,只是接收的参数形式不同
1 2 3 4 5 6 7
| Function.prototype._apply = function(context = window, args = []) { const key = Symbol() context[key] = this const result = context[key](...args) delete context[key] return result }
|
bind
与 apply
,call
相同,只是返回的是函数
1 2 3 4 5 6 7 8 9 10
| Function.prototype._bind = function(context = window, ...args) { const fn = this return function F() { if (this instanceof F) { return new fn(...args, ...arguments) } else { return fn._apply(context, [...args, ...arguments]) } } }
|