JavaScript中call和apply函数的模拟实现

134 阅读1分钟

1、call函数

call函数有两个作用:1、改变this指向 2、执行当前函数

假如自己创造了一个call函数名叫myCall,先说下要实现的效果:

var foo = { value: 1 };

function bar(name, age) {

return {

value: this.value,

name,

age,

}};

console.log(bar.myCall(foo, 'kobe', 38));

// 结果输出 {value: 1, name: "kobe", age: 38}


myCall函数具体实现:

Function.prototype.myCall = function (context) {

var context = context || window; // 如果context为null,则指向全局对象

context.fn = this; // 为对象添加该函数

var args = [];

for(var i = 1; i< arguments.length; i++) {

args.push('arguments['+i +']');

}

var result = eval('context.fn(' + args + ')'); // eval函数的作用是将参数里的字符串当做js代码执行

delete context.fn;

return result;

}

2、apply函数

call()方法的作用和 apply() 方法类似,区别就是call()方法接受的是参数列表,而apply()方法接受的是一个参数数组

假如自己创造了一个apply函数名叫myApply,想实现的结果:

var numbers = [5, 6, 2, 3, 7];

var max = Math.max.myApply(null, numbers);

// 输出结果5

myApply函数的具体实现:

Function.prototype.myApply = function (context, arr) {

var context = Object(context) || window;
context.fn = this;

var args = [];

if(!arr) {

return context.fn()

}; 

 for (var i = 0; i< arr.length; i++) {

args.push('arr['+i+']'); 

 }

var result = eval('context.fn('+args+')');

delete context.fn;

return result;

}