JS bindを徹底的に理解する
7882 ワード
冴羽大人はビッド接続を分析する:https://github.com/mqyqingfeng/Blog/issues/12 次は鶏肉料理の逐句分析です.
Function.prototype.bind = function(context) {
// bind, bind
if(this instanceof !== 'function') {
throw new Error(' , bind !')
}
// arguments , arguments,
let arg = Array.prototype.slice.call(arguments, 1) // [...arguments].slice(1)
// this , this, window
let that = this
//call
let fBound = function() {
// bind , ,secoundArg
let secoundArg = Array.prototype.slice.call(arguments)
/*
return ? context, arg.concat(secoundArg) ?
, bind , new , bind ,bind , this bar, obj
*/
return that.apply(this instanceof fBound ? this : context, arg.concat(secoundArg))
}
// prototype prototype,
fBound.prototype = this.prototype
return fBound
}
var value = 2;
var foo = {
value: 1
};
call :
var foo = {
value : 1
}
function bar(name, age) {
this.habit = 'shopping';
console.log(this.value); // undefined this obj, new
console.log(name); // daisy
console.log(age); // 18
}
bar.prototype.friend = 'kevin';
var bindFoo = bar.bind(foo, 'daisy');
var obj = new bindFoo('18');
// var obj = new bindFoo();
console.log(obj.habit); // shopping
console.log(obj.friend); // kevin