码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2017-03-22 23:40:34      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:node.js(七)——http作用域、上下文

http源码解读


什么是作用域?

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

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

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

实例如下:

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()

执行结果如下:

技术分享

什么是上下文?

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

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

代码如下:

第一种

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

pet.speak()

执行结果如下:

技术分享


第二种:

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

pet(‘...‘)

执行结果如下:

技术分享


第三种:

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()

执行结果如下:

技术分享


提出上下文是为了引出函数所拥有的两个方法: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‘)

运行结果如下:

技术分享


利用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()

运行结果如下:

技术分享


这就是call和apply的用法

本文出自 “IT菜鸟” 博客,请务必保留此出处http://mazongfei.blog.51cto.com/3174958/1909396

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

标签:node.js(七)——http作用域、上下文

原文地址:http://mazongfei.blog.51cto.com/3174958/1909396

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!