• js的几个可能不清晰的问题



    一、关于全局变量的


    var test=function(){

        var a=1;

        setTimeout(function(){

            console.log(a);

            a=2;

        },1000);

        a=3;

        setTimeout(function(){

            console.log(a);

            a=4;

        },2000);

    };

    test();

    结果是3,2;

    共享内存。setTimeout等异步,是取现在当时的a的值。执行第一个setTimeout的时候,a=3,已经执行了。


    二、全局变量和new变成全局的

    var foo=10;

    var a=1;

    var  main = function (){

    //a=10;

    console.log(a);

    a=20;

    console.log(this.foo);

    this.foo=foo;

    console.log(this.foo);

    foo=1000;

    console.log("111111111111");

    }

    var s=main();

    var d=new main();


    1

    10

    10

    111111111111


    20

    undefined

    1000

    111111111111

    不加new 都是全局的,this指向的全局变量。所以第一个就取得是全局的值。


    第二个加new 了,this.foo指向的是自己,没有定义于是就报undefined。外面a foo等是全局变量,main(),执行后,a已经变成20了,foo也变成1000了,所以值发生变化了,因为全局变量。




    var foo=10;

    var a=1;

    var  main = function (){

    //a=10;

    console.log(a);

    a=20;

    console.log(this.foo);

    this.foo=foo;

    console.log(this.foo);

    foo=1000;

    console.log("111111111111");

    }

    //var s=main();

    var d=new main();


    如果不执行第一个,结果发生变化。可以发现其实是全局变量的修改。

    1

    test.html (第 57 行)


    undefined

    test.html (第 59 行)


    10

    test.html (第 61 行)


    111111111111



    三、快速的判断Array类型


      var toString = Object.prototype.toString;

      var isArray = Array.isArray || function(val) {

        return toString.call(val) === '[object Array]';

      };


      function isString(val) {

        return toString.call(val) === '[object String]';

      }


      function isFunction(val) {

        return toString.call(val) === '[object Function]';

      }


    四、attribute和Property的区别


    attribute

    input节点有很多属性(attribute):‘type’,'id','value','class'以及自定义属性,在DOM中有setAttribute()和getAttribute()读写DOM树节点的属性(attribute)

    PS:在这里的getAttribute方法有一个潜规则,部分属性(input的value和checked)通过getAttribut取到的是初始值,这个就很好的解释了之前的n1为1。

    Property

    javascript获取到的DOM节点对象,比如a 你可以将他看作为一个基本的js对象,这个对象包括很多属性(property),比如“value”,“className”以及一些方法,setAttribute,getAttribute,onclick等,值得注意的是对象的value的属性(property)取值是跟着输入框内的当前值一起更新的,这解释了之前的n2为什么为1000了。


    五、关于hasOwnPropery


  • 相关阅读:
    log日志框架和LocationAwareLogger问题
    Eclipse 各种小图标的含义
    自定义log4j日志级别
    在Tomcat配置JNDI数据源的三种方式
    mybatis中"#"和"$"的区别
    Postman用法简介-Http请求模拟工具
    mustache模板技术(转)
    VS的编译选项
    Java Service Wrapper简介与使用
    还活着
  • 原文地址:https://www.cnblogs.com/danghuijian/p/4399905.html
Copyright © 2020-2023  润新知