试着跑一下如下代码:
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
。
![](https://img.haomeiwen.com/i13017484/6d69a22820730b0c.png)
思考一下为什么:
其实原因很简单,此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();
}
网友评论