学习之apply,call,bind实现
Posted meetqy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了学习之apply,call,bind实现相关的知识,希望对你有一定的参考价值。
目录
apply
简单说:创建一个新方法,用eval执行,完了之后删除掉,最后返回执行的结果。
Function.prototype.applyCopy = function(context) {
context.fn = this;// 谁调用 this就是谁
var args = arguments[1];
if(!args || args.length == 0) return context.fn();
var result = eval('context.fn("'+args.toString()+'")');
delete context.fn;
return result;
};
call
Function.prototype.callCopy = function(context) {
var args = [].shift.applyCopy(arguments);
return this.applyCopy(this, [args]);
}
bind
Function.prototype.bindCopy = function(context) {
var fn = this;
return function() {
return fn.apply(context, arguments[1]);
}
}
demo
var s = {
desc: 's.desc',
name: '你好',
}
var name = 'window';
var desc = 'window => this'
function sayHi() {
return {
name: this.name,
desc: this.desc,
}
}
console.log(sayHi());
console.log(sayHi.bindCopy(s)());
console.log(sayHi.call(s));
console.log(sayHi.apply(s));
总结:apply是基础,call,bind都是在apply的基础上实现的。
以上是关于学习之apply,call,bind实现的主要内容,如果未能解决你的问题,请参考以下文章
JavaScript中call,apply,bind方法的总结
JavaScript中call,apply,bind方法的总结
JavaScript中call,apply,bind方法的总结