// 手写 apply
Function.prototype.newApply = function (context, args) {
// 判断 this 是否为函数
if (typeof this !== 'function') {
throw new TypeError('Not a Function')
}
// 判断传入参数是否为空
context = context || window
args = args ? args : []
// 为 context 增添属性 fn
context.fn = this
// 通过隐式绑定调用函数
const result = context.fn(...args)
// 删除添加的属性
delete context.fn
return result
}
// 手写 call
Function.prototype.newCall = function (context, ...args) {
if (typeof this !== 'function') {
throw new TypeError('Not a Function')
}
context = context || window
args = args ? args : []
context.fn = this
const result = context.fn(...args)
delete context.fn
return result
}
// 手写 bind
Function.prototype.newBind = function (context, ...args) {
if (typeof this !== 'function') {
throw new TypeError('Not a Function')
}
args = args ? args : []
const fn = this
return function newFn(...newFnArgs) {
if (this instanceof newFn) {
return new fn(...args, ...newFnArgs)
}
return fn.apply(context, [...args, ...newFnArgs])
}
}
笔记
- call、apply、bind 三者区别
fn.call(obj, 1, 2); // fn立即执行
fn.bind(obj, 1, 2); // fn不执行
fn.apply(obj, [1, 2]);
- this 绑定的四种方式
-
默认绑定:作用于函数直接调用的情况下,此时this指向全局对象,但严格模式下this指向
-
隐式绑定:this指向它的调用者,即谁调用函数,他就指向谁
-
显式绑定:通过call、apply或bind实现
-
new绑定:
使用new操作符时实际做了四件事:
① 创建一个全新的对象
② 执行原型链接,使新对象的__proto__指向原函数的prototype
③ 这个新对象会被绑定到构造函数中的this
④ 执行构造函数,判断返回值,如果为对象,则返回这个值,否则返回默认创建的对象优先级:new > 显式 > 隐式 > 默认。