node.js学习笔记--HTTP之了解上下文

注:此博客是在学习进击Node.js基础(一)这门课程时的学习笔记,感谢Scott老师的课程。

一、this上下文的理解

this通常指向了当前函数的拥有者。

以下是三种用法

1. 在对象里的函数的this

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

pet是一个对象。执行上面代码,返回:

> lalala 
> true

这里this指向了pet这个变量。

2. 在全局的函数的this

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

pet('lalala')

执行后返回:

> lalala


//这一大堆是最顶层的global变量的所有参数

> true

这里的this指向了global变量(是pet()函数的拥有者)因为pet()在全局里

3. 在函数内部的函数的this,指向调用函数的对象

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

var cat = new Pet('Miao')  //new了一个实例对象

cat.speak()

返回:

> Miao
> {words: 'Maio', speak:[Function]}

其中 {words: 'Maio', speak:[Function]} 就是cat这个实例对象。

这里的this指向了cat这个实例对象

二、通过调用,改变函数执行的上下文

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

pet.speak('Speak')

//retuen Speak ...

var dog = {
	words:'Wang'
}
//调用Pet的speak函数
pet.speak.call(dog,'Speak')

返回:

> Speak Wang

通过call函数把this从pet变成指向dog。可以用在调用某个方法时想指定另一个对象为该方法的上下文。

此外,改变上下文也可以方便的使用继承。

三、通过调用实现继承,call和apply都可以用

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

function Dog(words){
	Pet.call(this, words)
	//通过call把指向Pet的指针指向Dog,使Dog有Pet的函数方法
	//Pet.apply(this, arguments) //aruguments传的是类数组
}

var dog = new Dog('Wang')

dog.speak()

返回:

> Wang

通过call把指向Pet的指针指向Dog,使Dog有Pet的函数方法

Guess you like

Origin blog.csdn.net/sriting/article/details/79630279