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
  • 相关阅读:
    商户编号前三位代码对应的收单机构大全
    使用邮件模板(freemarker.jar)发送邮件
    Struts2自定义拦截器
    如何在jsp页面显示存储在数据库的图片
    正则表达式 大于0的数字(包含小数)
    Linux的关机命令
    maven的下载和安装
    web.py的安装
    安装第三方插件BeautifulSoup
    myeclipse离线安装pydev插件
  • 原文地址:https://www.cnblogs.com/JinQing/p/6842120.html
Copyright © 2011-2022 走看看