JavaScript interview question summary series (8)

8. JavaScript-this object

this object

  • this always refers to the direct caller of the function (not the indirect caller)

  • If there is a new keyword, this points to the new object

  • In the event, this points to the object that triggered the event. In particular, this in attachEvent in IE always points to the global object Window

  • For anonymous functions or directly called functions, this points to the global context (browser is window, NodeJS is global)

  • Of course, there is also the arrow function of es6. The direction of the arrow function depends on the position of the arrow function declaration. Where it is declared, this points to where

  • this, the context of function execution, can change the direction of this through apply, call, and bind.

call()、apply()、bind()

  • The difference between call() and apply()

    • The parameter passed in call() is a single parameter, there can be multiple;
    • The parameter passed in apply() is an array
  • bind returns a function that can be currried, which is a strong binding.

  • How to implement a bind() function?

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 is to return a reference to the function, which called the current function;
  • callee is to return the function being executed, that is, the text of the specified function object

Reference link :
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

Guess you like

Origin blog.csdn.net/ZxxSteven/article/details/103064393