RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
Node.js(七)——HTTP作用域、上下文

http源码解读

创新互联建站-专业网站定制、快速模板网站建设、高性价比石河子网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式石河子网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖石河子地区。费用合理售后完善,10年实体公司更值得信赖。

什么是作用域?

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

作用域分局部作用域和全局作用域,同时作用域往往和变量有关系,

处在局部作用域里面可以访问到全局作用域的变量,反之则访问不到

实例如下:

var globalVariable = 'This is global variable'

function globalFunction(){
	var localVariable ='This is local variable'
	
	console.log('Visit global/local variable')
	console.log(globalVariable)
	console.log(localVariable)
	
	globalVariable = 'This is changed variable'
	console.log(globalVariable)
	
	function localFunction(){
		var innerLocalVariable = 'This is inner local variable'
		
		console.log('Visit global/local/inner variable')
		console.log(globalVariable)
		console.log(localVariable)
		console.log(innerLocalVariable)
	}
	localFunction()
}

globalFunction()

执行结果如下:

Node.js(七)——HTTP作用域、上下文

什么是上下文?

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

常常代表this变量的值以及它的指向,它决定一个函数怎么被调用,当这个函数作为一个对象的方法被调用时this总是指向调用这个方法的对象

代码如下:

第一种

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

pet.speak()

执行结果如下:

Node.js(七)——HTTP作用域、上下文

第二种:

function pet(words){
	this.words = words
	console.log(this.words)
	
	//这个this指向顶层的global对象
	console.log(this ===  global)
}

pet('...')

执行结果如下:

Node.js(七)——HTTP作用域、上下文

第三种:

function Pet(words){
	this.words = words
	this.speak = function(){
		console.log(this.words)
		//此时的this指向的谁?cat对象
		console.log(this)
	}
}

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

执行结果如下:

Node.js(七)——HTTP作用域、上下文

提出上下文是为了引出函数所拥有的两个方法:call和apply,可以改变上下文执行对象,可以在自定义上下文中执行函数,作用是一样的

只是用法有区别

call函数需要一个参数列表,apply允许你传递一个参数作为数组,具体的是作用呢是调用一个对象的方法以另一个对象替换当前对象,其实就是更改当前对象的this指向的内容,标准一点就是:以某个方法当做指定某个对象的方法被执行

示例如下:

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

//pet.speak('Speak')
var dog = {
	words:'Wang'
}

//让dog也能有speak方法
pet.speak.call(dog,'Speak')

运行结果如下:

Node.js(七)——HTTP作用域、上下文

利用call和apply可以方便的实现继承

function Pet(words){
	this.words = words
	this.speak = function(){
		console.log(this.words)
	}
}

function Dog(words){
	Pet.call(this,words)
	//Pet.apply(this,arguments)
}

//通过new生成实例对象
var dog = new Dog('Wang')
dog.speak()

运行结果如下:

Node.js(七)——HTTP作用域、上下文

这就是call和apply的用法


本文名称:Node.js(七)——HTTP作用域、上下文
浏览地址:http://sczitong.cn/article/ghdhjj.html