前端面试js篇

75 道 JavaScript 面试题

前端跨域解决方案

通过HTTP Header控制缓存

箭头函数的this 

函数可以运行在不同的环境,需要有一种机制,能在函数体内部获得当前的运行环境(执行上下文 context)。
所以 this 就出现了,它的设计目的就是在函数体内部,指代函数当前运行的环境。
this.a = 20

var test = {
  a: 40,
  init: function () {
    console.log('=xu= test.init', this.a) // 注意箭头函数的作用。若换成普通函数则是另一种表现。
    function go () {
      this.a = 60 // 优先于prototype
      console.log('=xu= 函数go', this.a)
    }
    go.prototype.a = 50
    return go
  }
}

// var p = test.init()
// p()
// new(test.init())()

var modify = {
  a: 99
}

var m = test.init.bind(modify)
m()

bind的实现

if (!Function.prototype.bind) {
  Function.prototype.bind = function(oThis) {
    if (typeof this !== 'function') {
      // closest thing possible to the ECMAScript 5
      // internal IsCallable function
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
    }

    var aArgs   = Array.prototype.slice.call(arguments, 1),
        fToBind = this,
        fNOP    = function() {},
        fBound  = function() {
          // this instanceof fBound === true时,说明返回的fBound被当做new的构造函数调用
          return fToBind.apply(this instanceof fBound
                 ? this
                 : oThis,
                 // 获取调用时(fBound)的传参.bind 返回的函数入参往往是这么传递的
                 aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    // 维护原型关系
    if (this.prototype) {
      // 当执行Function.prototype.bind()时, this为Function.prototype 
      // this.prototype(即Function.prototype.prototype)为undefined
      fNOP.prototype = this.prototype; 
    }
    // 下行的代码使fBound.prototype是fNOP的实例,因此
    // 返回的fBound若作为new的构造函数,new生成的新对象作为this传入fBound,新对象的__proto__就是fNOP的实例
    fBound.prototype = new fNOP();

    return fBound;
  };
}

 

 

posted on 2021-01-13 17:55  dawnxuuu  阅读(94)  评论(0编辑  收藏  举报

导航