zoukankan      html  css  js  c++  java
  • 什么是作用域?什么是上下文?浅解

    作用域和调用函数访问变量的能力有关

    作用域:分为局部作用域和全局作用域,处在局部作用域里面可以访问到全局作用域的变量,而在局部作用域外面就访问不到局部作用域里面所声明的变量

    var globalVariable = 'this is ';  //全局变量(全局作用域)
    function globalFunction(){  //局部作用域
        var localVariable = 'this is local';
        console.log('visit global/local');
        console.log(globalVariable);
        console.log(localVariable);
    
        globalVariable = 'this is change';
        console.log(globalVariable);
    
        function localFunction(){
            var innerLocalVariable = 'this is inner local';
            console.log(innerLocalVariable);
            console.log(localVariable);
            console.log(globalVariable);  //输出的是已改变的globalVariable = 'this is change'
        }
        localFunction();
    }
    globalFunction();

    上下文总是this这个关键字有关,是调用当前代码的引用

    上下文:

    //这里的this 指向的是pet
    var pet = {
        words:'...',
        speak:function(){
            console.log(this.words);  //输出...
            console.log(this === pet); //输出 true
        }
    };
    pet.speak();
    
    //这里的this 指向的是global  也就是nodeJs的顶层 相当于js window
    function pet(words){
        this.words = words;
        console.log(this.words);
        console.log(this === global)
    }
    pet('...');
    
    
    //这里的this 指向的是新创建的函数cat
    function pet(words){
        this.words = words;
        this.speak = function(){
            console.log(this.words); //输出Miao words:'Miao',speak:[Function]
        }
    }
    var cat = new pet('Miao');
    cat.speak();

    call apply : 改变上下文的执行,也就是this 指向

    //通过call 改变this 指向   改变之后pet.speak this 指向dog对象
    var pet = {
        words:'...',
        speak:function(say){
            console.log(say + '' + this.words)
        }
    };
    var dog = {
        words:'Wang'
    };
    pet.speak.call(dog,'Speak');   //输出 speak Wang
  • 相关阅读:
    finalShell 文件上传拖拽失败
    centos6.x 启动docker报错
    笔记本查看当前登录用户
    保存文件到D盘时显示“你没有权限在此文件夹中保存文件,请联系管理员“其他文件夹正常?
    关于MongoDB配置文件的一个小细节
    ubuntu: mongoDB安装,无需下载
    Java 连接虚拟机中MongoDB 所需依赖
    信息知识竞赛刷题助手
    python超多常用知识记录
    python字典键或值去重
  • 原文地址:https://www.cnblogs.com/JinQing/p/6842120.html
Copyright © 2011-2022 走看看