Description bind
function-bind.js
module . exports = Function . bind || function bind ( that /* , ...args */ ) {
// 判断是否是一个函数
var F = aCallable ( this ) ;
var Prototype = F . prototype ;
// 拿到除that之外的函数
var partArgs = arraySlice ( arguments , 1 ) ;
// 返回的函数
var boundFunction = function bound ( /* args... */ ) {
// 拼接参数
var args = concat ( partArgs , arraySlice ( arguments ) ) ;
// 重点!!
// 判断this是否是boundFunction的实例
// 函数bind之后的函数再new出一个实例,这个实例其实是通过,原函数new出的实例,并不会更改this指向
return this instanceof boundFunction ? construct ( F , args . length , args ) : F . apply ( that , args ) ;
} ;
// 继承this函数的原型
if ( isObject ( Prototype ) ) boundFunction . prototype = Prototype ;
return boundFunction ;
} ;
var construct = function ( C , argsLength , args ) {
if ( ! hasOwn ( factories , argsLength ) ) {
for ( var list = [ ] , i = 0 ; i < argsLength ; i ++ ) list [ i ] = 'a[' + i + ']' ;
// 通过Function创建函数
// 创建出的函数为
// ƒ anonymous(C,a
// ) {
// return new C(a[0],a[1])
// }
factories [ argsLength ] = Function ( 'C,a' , 'return new C(' + join ( list , ',' ) + ')' ) ;
} return factories [ argsLength ] ( C , args ) ;
} ;
例子
function a ( ) { }
function b ( ) { }
const c = a . _bind ( b )
const d = new c ( 'a' , 'c' , 'd' )
d为a函数bind之后的函数new出的实例对象
construct函数返回出的函数为
ƒ anonymous ( C , a ) {
// C是通过boundFunction闭包保存的例子中的a函数
return new C ( a [ 0 ] , a [ 1 ] , a [ 2 ] )
}
Reactions are currently unavailable
You can’t perform that action at this time.
bind
function-bind.js
例子
d为a函数bind之后的函数new出的实例对象construct函数返回出的函数为