JavaScript面試題總結系列(八)

8. JavaScript - this對象

this對象

  • this總是指向函數的直接調用者(而非間接調用者)

  • 如果有new關鍵字,this指向new出來的那個對象

  • 在事件中,this指向觸發這個事件的對象,特殊的是,IE中的attachEvent中的this總是指向全局對象Window

  • 對於匿名函數或者直接調用的函數來說,this指向全局上下文(瀏覽器爲window,NodeJS爲global)

  • 當然還有es6的箭頭函數,箭頭函數的指向取決於該箭頭函數聲明的位置,在哪裏聲明,this就指向哪裏

  • this,函數執行的上下文,可以通過apply,call,bind改變this的指向。

call()、apply()、bind()

  • call()和apply()區別
    • call() 傳入的參數是單個的參數,可以有多個;
    • apply() 傳入的參數是一個數組
  • bind 返回一個函數,可以實現柯里化,是一個強綁定。
  • 如何實現一個bind()函數?
Function.prototype.bind2 = function (context) {

    if (typeof this !== "function") {
      throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
    }

    var self = this;
    var args = Array.prototype.slice.call(arguments, 1);

    var fNOP = function () {};

    var fBound = function () {
        var bindArgs = Array.prototype.slice.call(arguments);
        return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
    }

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();
    return fBound;
}

callee、caller

  • caller是返回一個對函數的引用,該函數調用了當前函數;
  • callee是返回正在被執行的function函數,也就是所指定的function對象的正文

參考鏈接
http://blog.poetries.top/FE-Interview-Questions/base/#_70-javascript%E4%B8%ADcallee%E5%92%8Ccaller%E7%9A%84%E4%BD%9C%E7%94%A8%EF%BC%9F https://github.com/mqyqingfeng/Blog/issues/12
https://juejin.im/post/5b3c3377f265da0f8f20131f
https://juejin.im/post/59093b1fa0bb9f006517b906

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章