bind返回函數被當成構造函數的情況
在MDN中有這麼一句話
bind()中的第一個參數:調用綁定函數時作爲 this 參數傳遞給目標函數的值。
如果使用new運算符構造綁定函數,則忽略該值
那麼這句話啥意思呢??
首先,我們都知道bind()會返回一個新的函數,如果這個返回的新的函數作爲構造函數創建一個新的對象,那麼此時this不再指向傳入給bind的第一個參數,而是指向用new創建的實例
function func (name) {
console.log(this);
this.name = name
}
func.prototype.hello = function () {
console.log(this.name);
}
let obj = {
a: 1,
say: function () {
console.log('say');
}
}
let newObj = func.bind(obj)
newObj()
//{a:1, say:f} 此時this指向obj
function func (name) {
console.log(this);
// func{}
this.name = name
}
func.prototype.hello = function () {
console.log(this.name);
}
let obj = {
a: 1,
say: function () {
console.log('say');
}
}
let newObj = func.bind(obj)
// 若將返回的函數作爲構造函數
let o = new newObj('seven')
//this的指向發生了改變,指向原函數,並且可以訪問原函數的原型
console.log('o', o);
// func{name:'seven'}
o.hello() // seven