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
  • 相关阅读:
    概率论02 概率公理-集合
    概率论1 计数-排列-组合
    matplotlib 练习
    python itertools模块练习
    主观世界的破碎与重建——湖畔大学的失败课外课
    Python操作MongoDB(PyMongo模块的使用)
    python操作json数据格式--基础
    linux shell awk实现实时监控网卡流量脚本
    Python 的十个自然语言处理工具
    实现优先级队列 --heapq模块
  • 原文地址:https://www.cnblogs.com/JinQing/p/6842120.html
Copyright © 2011-2022 走看看