06慕课网《进击Node.js基础(一)》作用域和上下文

作用域

调用函数访问变量的能力

//全局变量
var globalVariable = 'This is global variable'
//全局函数
function globalFunction(){
    //局部变量
    var localVariable =  'This is local variable'
    console.log('visit gloabl/local variable')
    console.log(globalVariable)
    console.log(localVariable)

    globalVariable = 'this is change variable'

    console.log(globalVariable)
    //局部函数
    function loaclFunction(){
        //局部变量
        var innerLocalVariable = 'this is inner local variable'
        console.log('visit gloabl/local/innerLocal variable')
        console.log(globalVariable)
        console.log(localVariable)
        console.log(innerLocalVariable)
    }
    //作用域内可访问局部函数
    loaclFunction()

}
//在全局不能访问局部变量和函数
globalFunction()

上下文

和this关键字有关,是调用当前可执行代码的对象的引用

this指向函数拥有者,只能在函数中使用

this指向构造函数
var pet = {
    words:'..',
    speak:function(){
        console.log(this.words)
        console.log(this==pet)
    }
}

pet.speak()

this指向全局对象
function pet(words){
    this.words = words
    console.log(this.words)
    console.log(this==global)
}
//this指向了全局global对象
pet('..')

this指向实例对象
function Pet(words){
    this.words = words
    this.speak = function(){
        console.log(this.words)
        console.log(this)
    }
}

var cat = new Pet('Miao')
cat.speak();

使用call和apply改变上下文引用对象

this指向引用方法的对象
var pet = {
    words:'..',
    speak:function(say){
        console.log(say + ' ' + this.words)
    }
}

pet.speak('haha')

使用call-apply
var pet = {
    words:'..',
    speak:function(say,free){
        console.log(say + ' ' + free+ ' '+ this.words)
    }
}

var dog={
    words:'wawa'
}

pet.speak.call(dog,'haha','lala')
pet.speak.apply(dog,['haha','lala'])

使用call和apply方便实现继承
function Pet(words){
    this.words = words

    this.speak = function(){
        console.log(this.words)
    }
}
//Dog继承Pet,拥有了Pet的speak方法
function Dog(words){
    Pet.call(this,words)
}

var dog = new Dog('wawa')

dog.speak()

猜你喜欢

转载自www.cnblogs.com/-beauTiFul/p/9095696.html