apply、call、bind
apply、call、bind实现原理
一、apply
语法:
fn.apply(thisArg[, argsArray])实现:
Function.prototype.myApply = function (context, args) {
//第一个参数为null或者undefined时,this指向全局对象window;值为原始值时(例如fn.apply('hello')),this指向该原始值的自动包装对象,如 String、Number、Boolean
context = (context ?? window) || Object(context);
//第二个参数可以不传,但类型必须为数组或者类数组
if (args && !Array.isArray(args)) {
throw new Error('第二个参数必须为数组')
}
//为了避免函数名与上下文(context)的属性发生冲突,使用Symbol类型作为唯一值
const key = Symbol();
context[key] = this; // this === fn
const result = args ? context[key](...args) : context[key]();
//函数执行完成后删除该属性
delete context[key];
return result;
}
function sayHi(msg) {
console.log(this);
console.log(`Hi, ${this.name} ${msg}`);
}
sayHi.myApply(undefined) // window
sayHi.myApply(null) // window
sayHi.myApply(1) // Number
sayHi.myApply('11') // String
sayHi.myApply(true) // Boolean
sayHi.myApply({ name: 'yuyy' }, ['how old are you?'])思路:
二、call
语法:
实现:
思路:
三、bind
语法:
实现:
思路:柯里化方式实现
总结
Last updated