zoukankan      html  css  js  c++  java
  • javascript 的 this , js 线程

    1. this 知多少

      以为自己对this 已经了解了,但是昨天看了一道题目,发现并非如此,先看代码

     1         c = 999;
     2         var c = 888;
     3         console.log(this.c); //888
     4         function b (x, y, c) {
     5             c = 6;
     6             arguments[2] = 10;
     7             console.log(c); //10
     8             console.log(this.c); //888
     9              
    10             var c = 6;
    11             console.log(c); //
    12             console.log(this.c); //
    13         }
    14         b(1, 2, 3, 4);

      在外部的c == var c == this.c == window.c . 那么在function b 里面的 this.c 为什么等于 window.c 呢? 查阅原来js 里面的this 指向当前的对象,那么function b 现在全局环境中运行,因此 this 是指向window 的。

      那么我想改变this 的指向,怎么做呢?

     1 c = 999;
     2         var c = 888;
     3         console.log(this.c); //888
     4         function b (x, y, c) {
     5             c = 6;
     6             arguments[2] = 10;
     7             console.log(c); //10
     8             console.log(this.c); //888
     9              
    10             var c = 6;
    11             console.log(c); //
    12             console.log(this.c); //
    13         }
    14         b(1, 2, 3, 4);
    15 
    16         o = {
    17             c :77
    18         };
    19 
    20         o.b = b;
    21         o.b();

      这个时候,this 就指向o 了,输出结果也就不是888了 而是 77,可以验证。

    2.JS单线程

            var start = new Date();
            setTimeout(
                function(){
                    var end = new Date();
                    console.log(end - start);
                },
                1000
            )
            while(new Date() - start < 2000);

      这个结果应该是大于2000的。

    3.一道容易错的

    1 function a(){ return a;  /*var b = 0;return b;*/}
    2 console.log(new a() instanceof a);//false

    因为a 是 return a ,那么 a instanceof a ,当然是错误的了。

      function a (){}

      var b = new a;

      b instanceof a; //true 这个时候就是对的了

    疯癫不成狂,有酒勿可尝;世间良辰美,终成水墨白。
  • 相关阅读:
    事务传播机制,搞懂。
    洛谷 P1553 数字反转(升级版) 题解
    洛谷 P1200 [USACO1.1]你的飞碟在这儿Your Ride Is Here 题解
    洛谷 P1055 ISBN号码 题解
    洛谷 P2141 珠心算测验 题解
    洛谷 P1047 校门外的树 题解
    洛谷 P1980 计数问题 题解
    洛谷 P1008 三连击 题解
    HDU 1013 题解
    HDU 1012 题解
  • 原文地址:https://www.cnblogs.com/chuyu/p/3196472.html
Copyright © 2011-2022 走看看