zoukankan      html  css  js  c++  java
  • js 变量作用域 与 this

    首先说下js作用域链:由于js变量都是对象的属性,对象又可以是对象的属性,最终到达window,所以变量-------window就是一条作用域链;

    先说下变量作用域:

    var a=10;
    function test(){
    console.log(a);----------undefined
    var a = 5;

    console.log(a);----------5
    }
    test();

    test() 方法内:console.log(a)中变量a寻找自己的定义,发现var a = 5;已经有定义了,所以a的定义就是局部变量。这个时候由于console.log(a)的时候a还没有被赋值,所以undefined

    再看this:

    var a=10;
    function test(){

    console.log(a);
    this.a = 5;
    var a =5;

    }

    test();---undefined
    console.log(a);------5

    this发现基本上都是指向window,都会改变全局变量。

    除了

    var a=10;
    function test(){

    console.log(a);
    this.a = 5;


    }

    var t = new test(); ------10
    console.log(a);---10

    这个时候 this 属于函数t--不会改变全局变量

  • 相关阅读:
    命名规范
    操作文件和目录
    使用本地shadow socks代理
    发送邮件
    sql参数化
    定义常量
    获取嵌套字典值的方法
    通过字符串调用函数
    用字典优化过长的if 语句
    操作文件和目录
  • 原文地址:https://www.cnblogs.com/qianduanxiaocaij/p/4832315.html
Copyright © 2011-2022 走看看