NodeJS——HTTP源码解读

HTTP源码解读

变量作用域

【代码】

[root@localhost http]# vi scope.js

var gV = 'This is a global variable'
function globalFunction(){
    var lV = 'This is a local variable'
    console.log('Visit global/localvariables')
    console.log(gV)
    console.log(lV)
    gv = 'This is a changed variable'
    console.log(gV)
    function localFunction(){
        var iLV = 'This is a inner local variable'
        console.log('Visit global/local/innerLocal Variables')
        console.log(gV)
        console.log(lV)
        console.log(iLV)
    }
    localFunction()
}
globalFunction()

【结果】

[root@localhost http]# node scope.js
Visit global/localvariables
This is a global variable
This is a local variable
This is a global variable
Visit global/local/innerLocal Variables
This is a global variable
This is a local variable
This is a inner local variable

上下文与this

指向当前函数的拥有者。

【代码1】

[root@localhost http]# vi context.js

var pet = {
    words:'...',
    speak:function(){
        console.log(this.words)
        console.log(this === pet)
    }
}
pet.speak()

【结果】

[root@localhost http]# node context.js 
...
true

【代码2】

[root@localhost http]# vi ctx.js

function pet(words){
    this.words = words
    console.log(this.words)
    console.log (this===global)
}
pet('...')

【结果】

[root@localhost http]# node ctx.js 
...
true

【代码3】

[root@localhost http]# vi ctx2.js

function Pet(words){
    this.words = words
    this.speak = function(){
        console.log(this.words)
        console.log(this)
    }
}
var cat = new Pet('Miao')
cat.speak()

【结果】

[root@localhost http]# node ctx2.js 
Miao
Pet { words: 'Miao', speak: [Function] }

call、apply

【代码1】

[root@localhost http]# vi call_apply.js

var pet = {
    words:'...',
    speak:function(say){
        console.log(say+' '+this.words)
    }
}
var dog = {
    words:'Wang'
}
pet.speak.call(dog,'Speak')

【结果】

[root@localhost http]# node call_apply.js 
Speak Wang

【代码2】

[root@localhost http]# vi call_apply_extend.js

function Pet(words){
    this.words = words
    this.speak = function (){
        console.log(this.words)
    }
}
function Dog(words){
    Pet.call(this,words)
    //Pet.apply(this,arguments)
}
var dog = new Dog('Wang')
dog.speak()

【结果】

[root@localhost http]# node call_apply.js 
Speak Wang
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容