首页 > 代码库 > 什么是作用域?什么是上下文?浅解

什么是作用域?什么是上下文?浅解

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

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

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

 

什么是作用域?什么是上下文?浅解