有意思的一道阿里面试题

试着跑一下如下代码:

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();
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。