美文网首页
有意思的一道阿里面试题

有意思的一道阿里面试题

作者: Sczlog | 来源:发表于2019-03-22 10:40 被阅读0次

试着跑一下如下代码:

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();
}

相关文章

网友评论

      本文标题:有意思的一道阿里面试题

      本文链接:https://www.haomeiwen.com/subject/bjflvqtx.html