作者:
作者:xl
// call
Function.prototype.myCall = function (context) {
// 获取参数
let args = [...arguments].slice(1);
// 保存调用结果
let result = null;
// 判断 context 是否传入,如果未传入则设置为 window
context = context || window;
// 将函数设为对象的方法
context.fn = this;
// 调用函数
result = context.fn(...args);
// 属性删除
delete context.fn;
return result;
}
// apply
Function.prototype.myApply = function (context) {
let result = null;
// 判断 context 是否传入,如果未传入则设置为 window
context = context || window;
// 将函数设为对象的方法
context.fn = this;
if (arguments[1]) {
result = context.fn(...arguments[1]);
} else {
result = context.fn();
}
// 属性删除
delete context.fn;
return result;
}
作者:奥兰度
function myCall(fn, thisArg, ...args) {
if (typeof this !== "function") {
console.log("type error");
}
let res;
thisArg = thisArg || window;
thisArg.fn = fn;
result = thisArg.fn(...args);
delete thisArg.fn;
return result;
};
function myApply(fn, thisArg, argAry) {
if (typeof this !== "function") {
console.log("type error");
}
let res;
thisArg = thisArg || window;
thisArg.fn = fn;
result = thisArg.fn(argAry);
delete thisArg.fn;
return result;
};
作者:
作者:安静
Function.prototype.myCall = function (context, ...args) {
//这里默认不传就是给window,也可以用es6给参数设置默认参数
context = context || window
args = args ? args : []
//给context新增一个独一无二的属性以免覆盖原有属性
const key = Symbol()
context[key] = this
//通过隐式绑定的方式调用函数
const result = context[key](...args)
//删除添加的属性
delete context[key]
//返回函数调用的返回值
return result
}
Function.prototype.myApply = function (context, array) {
//这里默认不传就是给window,也可以用es6给参数设置默认参数
context = context || window
args = array ? array : []
//给context新增一个独一无二的属性以免覆盖原有属性
const key = Symbol()
context[key] = this
//通过隐式绑定的方式调用函数
const result = context[key](...args)
//删除添加的属性
delete context[key]
//返回函数调用的返回值
return result
}
function a (...args) {
console.log(args);
console.log(this.name);
}
a.myApply({name: 'zhangsan'}, [1,2,3])
作者:
作者: