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