試著跑一下如下代碼:
function removeUndefined() {
function lateBloomer() {
this.petalCount = Math.ceil(Math.random() * 12) + 1
}
lateBloomer.prototype.bloom = function () {
window.setTimeout(this.declare, 1000)
}
lateBloomer.prototype.declare = function() {
console.log('I am a beautiful flower with ' + this.petalCount + ' petals')
}
let f = new lateBloomer();
f.bloom();
}
會發現petalCount為 undefined
。
結果
思考一下為什么:
其實原因很簡單,此this非彼this,構造函數中的this指向對象本身,而普通函數的this則會指向windows。
所以最簡單的方法,調用構造函數不用this,直接指向windows。
function removeUndefined() {
function lateBloomer() {
window.petalCount = Math.ceil(Math.random() * 12) + 1
}
lateBloomer.prototype.bloom = function () {
window.setTimeout(this.declare, 1000)
}
lateBloomer.prototype.declare = function() {
console.log('I am a beautiful flower with ' + this.petalCount + ' petals')
}
let f = new lateBloomer();
f.bloom();
}
但這樣的話這道題就只解了一半。
這題的另一半考的是怎么去改變this的指向。
那么答案呼之欲出,bind
or apply
or call
讓lateBloomer本身去調用declare方法,此時的this就會都指向lateBloomer對象。
function removeUndefined() {
function lateBloomer() {
this.petalCount = Math.ceil(Math.random() * 12) + 1
}
lateBloomer.prototype.bloom = function () {
window.setTimeout(() => {
this.declare.call(f)
}, 1000)
}
lateBloomer.prototype.declare = function () {
console.log('I am a beautiful flower with ' + this.petalCount + ' petals')
}
let f = new lateBloomer();
f.bloom();
}