js总结之模拟bind

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
* @Author: changchang
* @github: https://github.com/changchangge
* @LastEditors: changchang
* @Date: 2019-02-27 16:40:50
* @LastEditTime: 2019-02-27 20:31:34
*/

/**
* @description: bind()方法创建一个新的函数,在调用时设置this关键字为提供的值。
* 并在调用新函数时,将给定列表参数作为原函数的参数序列的前若干项
*/

Function.prototype.bindTest=function (context){
if(typeof this !=="function"){
throw new Error("Function.prototype.bind-what is trying to be bound is not callable");
}
var self=this;
var args=Array.prototype.slice.call(arguments,1);
var fNOP=function (){};
var fBound=function (){
var bindArgs=Array.prototype.slice.call(arguments);
return self.apply(this instanceof fBound?this:context,args.concat(bindArgs));
}
fNOP.prototype=this.prototype;
fBound.prototype=new fNOP();
return fBound;
}
本文结束啦感谢您的阅读
undefined