Function.prototype.bind2 = function(context){ if (typeof this !== "function") { throw new Error("Function.prototype.bind - the object to be bound is not callable"); } var self = this var args = Array.prototype.slice.call(arguments,1) var fNOP = function () {}; var boundFN = function(){ var bindargs = Array.prototype.slice.call(arguments) self.apply(this instanceof self ? this: context,args.concat(bindargs)) } fNOP.prototype = this.prototype; boundFN.prototype = new fNOP() return boundFN}var foo = {name : 'xxx'}function bar (age,sex,tall){ this.tall = tall console.log(this.name); console.log(age); console.log(sex); console.log(this.tall);}var dd = bar.bind2(foo,12,'male')var cc = new dd('180cm')console.log(cc)
其中
var args = Array.prototype.slice.call(arguments,1)
arguments是具有length属性的对象,该操作可以将形似数据的对象转换成数据,并传入参数进行数组截取。另外,注意使用slice而不是splice,相同点:都会返回截取后的数组,不同点:splice会对原数组进行截取,slice不是对原数组有影响。