分号问题+函数中的this

2018-05-08  本文已影响0人  zhangjingbibibi

这篇文章写2个知识点:分号问题和函数中的this。

分号问题

var a = 3
  ;(function () {

  })()
  /*如果不加分号,就会变成这样
   错误理解
   var a = 3(function () {

   })();
  */

  var b = 4
  ;[1, 3].forEach(function () {

  })
  /*
   * 如果不加分号,就会变成这样
  错误理解
   var b = 4[3].forEach(function () {

   })
   */

函数中的this

 function Person(color) {
    console.log(this)
    this.color = color;
    this.getColor = function () {
      console.log(this)
      return this.color;
    };
    this.setColor = function (color) {
      console.log(this)
      this.color = color;
    };
  }

  Person("red"); //this是谁? window

  var p = new Person("yello"); //this是谁? p

  p.getColor(); //this是谁? p

  var obj = {};
  p.setColor.call(obj, "black"); //this是谁? obj

  var test = p.setColor;
  test(); //this是谁? window

  function fun1() {
    function fun2() {
      console.log(this);
    }

    fun2();
  }
  fun1(); //this是谁? window
上一篇下一篇

猜你喜欢

热点阅读