// call
// 参数:
// 第一个参数:改变到的对象
// 第二个参数:参数列表
Function.prototype.call = function(target, ...args){
const type = typeof target;
if(type !== 'function' || type !=='object'){
console.error('目标对象须是一个函数或者object数据类型的数据');
return;
}
const context = target || window;
const _property = Symbol('fn'); // 保证目标对象的属性不被篡改
context[_property] = this;
context[property](...args);
Reflect.deleteProperty(context, _property);
}
// apply
// 参数:
// 第一个参数:改变到的对象
// 第二个参数:参数数组
Function.prototype.apply = function(target, args){
const type = typeof target;
if(type !== 'function' || type !=='object'){
console.error('目标对象须是一个函数或者object数据类型的数据');
return;
}
const context = target || window;
const _property = Symbol('fn'); // 保证目标对象的属性不被篡改
context[_property] = this;
context[property](...args);
Reflect.deleteProperty(context, _property);
}
// bind
// 只改变 this 指向,不执行函数
Function.prototype.bind = function(target, ..._args){
const type = typeof target;
if(type !== 'function' || type !== 'object') {
console.error('目标对象须是一个函数或者object数据类型的数据');
return;
}
const context = target || window;
const _property = symbol('fn');
context[_property] = this;
// 闭包
return function(...args){
const params = [..._args, ...args];
context[_property](...params);
}
}
原生 js 实现 改变 this(call、apply、bind)
最新推荐文章于 2024-03-31 15:50:35 发布