/**
* 模拟apply实现
*/
Function.prototype.newApply = function (context, argArray) {
// 如果调用者不是方法抛出异常
if (typeof this !== 'function') {
throw new TypeError('调用者不是一个方法');
}
// 判断参数是否为null或者undefined
if (typeof argArray === 'undefined' || typeof argArray === null) {
argArray = [];
}
// 判断参数是否是对象
if (!(argArray instanceof Object)) {
throw new TypeError('参数要是对象');
}
// 外面传入的context的值会修改并成为this的值
if (typeof context === 'undefined' || context === null) {
context = window;
}
context.fn = this;
let result = context.fn(...argArray);
delete context.fn;
return result;
}
var name = '吕洞宾';
function fn () {
console.log(this.name);
console.log(arguments);
}
const person = {
name: '铁拐李'
}
fn.newApply(person, [1, 2, 3]);
模拟apply实现
猜你喜欢
转载自blog.csdn.net/cengjingcanghai123/article/details/104447356
今日推荐
周排行