源码:
支持new 绑定
//兼容IE6写法
var slice = Array.prototype.slice
function ieBind(ieThis) {
var args = slice.call(arguments, 1)
// this就是调用bind的函数
var fn = this
function fn2 () {
var args2 = slice.call(arguments, 0)
return fn.apply(fn2.prototype.isPrototypeOf(this) ? this : ieThis, args.concat(args2))
}
fn2.prototype = fn.prototype
return fn2
}
//es6写法
function _bind(obj, ...arg) {
const fn = this;// this就是调用bind的函数
function fn2 (...arg2) {
return fn.call(this instanceof fn2 ? this : obj, ...arg, ...arg2)
}
fn2.prototype = fn.prototype
return fn2
}
// module.exports = ieBind;
module.exports = _bind;
if (!Function.prototype.bind) {//polyfill
Function.prototype.bind = _bind
}
测试代码:
const bind = require('../src/index')
test1('测试bind2是否能用')
test2('测试是否能绑定this成功')
test3('测试this, a, b 绑定成功')
test4('测试this, a绑定成功后,传入b调用成功')
test5('new 的时候也绑定了a, b')
test6('new 的时候也绑定了a, b,并且函数中有 prototype.gogo')
function test1(message) {
console.log(message)
Function.prototype.bind2 = bind
console.assert(Function.prototype.bind2 !== undefined)
}
function test2(message) {
console.log(message)
Function.prototype.bind2 = bind
const f1 = function () {
return this
}
const newF1 = f1.bind2({name: 'he'},1,2)
console.assert(newF1().name === 'he')
}
function test3(message) {
console.log(message)
Function.prototype.bind2 = bind
const f1 = function (a, b) {
return [this, a, b]
}
const newF1 = f1.bind2({name: 'he'},111,2222)
console.assert(newF1()[0].name === 'he','this')
console.assert(newF1()[1] === 111,'a')
console.assert(newF1()[2] === 2222,'b')
}
function test4(message) {
console.log(message)
Function.prototype.bind2 = bind
const f1 = function (a, b) {
return [this, a, b]
}
const newF1 = f1.bind2({name: 'he'},111)
console.assert(newF1(2222)[0].name === 'he','this')
console.assert(newF1(2222)[1] === 111,'a')
console.assert(newF1(2222)[2] === 2222,'b')
}
function test5(message) {
console.log(message)
Function.prototype.bind2 = bind
const f1 = function (a, b) {
this.a = a
this.b = b
}
const f2 = f1.bind2(undefined, 111, 222)
const f3 = new f2()
console.assert(f3.a === 111,'a')
console.assert(f3.b === 222,'b')
}
function test6(message) {
console.log(message)
Function.prototype.bind2 = bind
const f1 = function (a, b) {
this.a = a
this.b = b
}
f1.prototype.gogo = function () {}
const f2 = f1.bind2(undefined, 111, 222)
const f3 = new f2()
console.assert(f3.a === 111,'a')
console.assert(f3.b === 222,'b')
console.assert(f1.prototype.isPrototypeOf(f3) ,'new后,原型是否继承')
console.assert(typeof f3.gogo === 'function')
}