美文网首页
分号问题+函数中的this

分号问题+函数中的this

作者: zhangjingbibibi | 来源:发表于2018-05-08 14:21 被阅读0次

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

    分号问题

    • js语句的后面可以不加分号
    • 是否加分号是编码风格问题,没有应不应该,只有你自己喜欢不喜欢
    • 在下面2种情况下不加分号会有问题
      • 小括号开头的前一条语句
      • 中方括号开头的前一句语句
    • 解决办法:在行首加分号
    • 强有力的例子:vue.js
    • 知乎热议:https://www.zhihu.com/question/20298345
    var a = 3
      ;(function () {
    
      })()
      /*如果不加分号,就会变成这样
       错误理解
       var a = 3(function () {
    
       })();
      */
    
      var b = 4
      ;[1, 3].forEach(function () {
    
      })
      /*
       * 如果不加分号,就会变成这样
      错误理解
       var b = 4[3].forEach(function () {
    
       })
       */
    

    函数中的this

    • this是什么?
      • 任何函数本质上都是通过某个对象来调用的,如果没有直接指定,那默认就是window
      • 所有函数内部都有一个变量this
      • 它的值是调用函数的当前对象
    • 如何确定this的值?
      • test() //window
      • p.test() //p
      • new test() //新创建的对象
      • p.call(obj) //obj
     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
    

    相关文章

      网友评论

          本文标题:分号问题+函数中的this

          本文链接:https://www.haomeiwen.com/subject/xxzirftx.html