バインド実装のシミュレーション方法
bind() 関数は新しい関数を作成します。bind() がコールされると、 bind の最初のパラメータとして新しい関数の this が指定され、 その他のパラメータは新しい関数のパラメータとして使用されます。
バインドとは何ですか?
通常の関数が thisポインタを変更する場合。
コンストラクタがプロトタイプのプロパティとメソッドを取得するため。
bind
バインディング関数の作成
var x = 10
var model = {
x: 100,
getX: function () {
console.log(this.x)
return this.x
}
}
model.getX()// 100
var getX = model.getX
getX() // 10 この時点で thisはウィンドウを実行する。
var newGetX = getX.bind(model)
newGetX() // 100
機能の迅速な使用
var unboundSlice = Array.prototype.slice
var slice = Function.prototype.apply.bind(unboundSlice)
function aa(1,2,3) {
console.log(arguments)
slice(arguments)
}
bind
Function.prototype.bind = function(conext, ...args) {
var self = this
var fNOP = function () {}
// 高階関数は関数を返す
var fbound = function() {
// 実行中に thisのポイントを変更する
self.apply(this instanceof self ? this : context,
args.concat(Array.prototype.slice.call(arguments)))
}
fNOP.prototype = this.prototype
fbounf.prototype = new fNOP()
return fbound
}