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

猜你喜欢

转载自blog.csdn.net/ZxxSteven/article/details/103064393
今日推荐