Function.prototype.bind2 = function (context) { var self = this; // 获取bind2函数从第二个参数到最后一个参数 var args = Array.prototype.slice.call(arguments, 1); returnfunction () { // 这个时候的arguments是指bind返回的函数传入的参数 var bindArgs = Array.prototype.slice.call(arguments); return self.apply(context, args.concat(bindArgs)); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var value = 2; var foo = { value: 1 }; functionbar(name, age) { this.habit = 'shopping'; console.log(this.value); // undefined console.log(name); // daisy console.log(age); // 18 } bar.prototype.friend = 'kevin'; var bindFoo = bar.bind(foo, 'daisy'); var obj = new bindFoo('18');
console.log(obj.habit); // shopping console.log(obj.friend); // kevin
1 2 3 4 5 6 7 8 9 10 11 12
Function.prototype.bind2 = function(context) { var self = this; var args = Array.prototype.slice.call(arguments, 1); var fBound = function () { var bindArgs = Array.prototype.slice.call(arguments); // 当作为构造函数时,this指向实例, // 当作为普通函数时,this 指向window, return self.apply(thisinstanceof fBound ? this : context, args.concat(bindArgs)); } fBound.prototype = this.prototype; return fBound; }
1 2 3 4 5 6 7 8 9 10 11 12
Function.prototype.bind2 = function(context) { 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(thisinstanceof fNOP ? this : context, args.concat(bindArgs)) } fNOP.prototype = this.prototype fBound.prototype = new fNOP(); return fBound; }
1 2 3 4 5 6 7 8 9
var value = 2; var foo = { value: 1, bar: bar.bind(null) } functionbar() { console.log(this.value); // 2 } foo.bar();
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Function.prototype.bind2 = function(context) { if (typeofthis !== "function") { thrownewTypeError("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(thisinstanceof fNOP ? this : context, args.concat(bindArgs)); } fNOP.prototype = this.prototype fBound.prototype = new fNOP(); return fBound; }