有意思的一道阿里面試題

試著跑一下如下代碼:

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();
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。