call apply 都能改变this 的指向,之间的区别在于call将函数参数单个传入,通过‘,’分开,apply通过数组的方式传递参数。。。
设置一些参数用来测试
var value = 'window'
var obj = {
value: 'hello'
}
function show(name, age) {
console.log(this.value)
return {
name: name,
age: age
}
}
改变this指向的原理大概是这个样子的
obj.show = show;
obj.show();
delete obj.show();
//很简单的过程,应该都能明白
在函数的原型链上封装两个函数
封装call函数
Function.prototype.newCall = function(){
var ctx = arguments[0] || window;
//第一个参数是改变this的对象
ctx.fn = this;
//将该函数赋给传入的对象
var args = [];
for(var i =1;i<arguments.length;i++){
args.push('arguments[' + i+ ']');
}
var result = eval('ctx.fn(' + args.join(',') + ')');
//eval能够将传入的字符串当做js语言执行
delete ctx.fn;
return result;
}
//var res = show.newCall(obj,'wcf',18); 测试输出
封装apply函数
Function.prototype.newApply = function (ctx, arr) {
var ctx = ctx || window;
ctx.fn = this;
var result;
if (!arr) {
result = ctx.fn();
} else {
var args = [];
for (var i = 0; i < arguments[1].length; i++) {
args.push('arguments[1][' + i + ']');
}
result = eval('ctx.fn(' + args.join(',') + ')');
}
delete ctx.fn;
return result;
}
//console.log(show.newApply(obj, ['www', 19]));测试输出