JavaScript中的上下文 -this-技术胖-胜洪宇关注web前端技术

183 阅读1分钟
原文链接: jspang.com

接触JavaScript这门语言也有几年了,但是对其中的上下文还是有些模糊,经常会踩坑。我决定用今天的时间好好学习一下这个this关键字。

我们先来看下边这段代码,这段代码中在对象pet(宠物)里有个this关键字,这个关键要看谁调用了它。最后一句pet.speak();显然是pet调用了它的方法,这是this就是pet对象。

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

此段代码输出了wangwang…,如果我们再加一个console.log(this===pet);我们会发现打出了true。

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

我们在写一个方法,里边有this关键字,然后调用它。因为我们是在node环境下,这是的this就是global全局对象,如果在web环境下就是window对象。

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

上边的代码打印出了wangwang…和true。说明这种情况this就是全局变量global。

我们再来看一下这端代码,这段代码是先定义了一个方法,然后用 new 关键字声明了一个cat的对象。这时候方法里面的this就是对象了。

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

我们可以看一下this打印的结果是Pet { words: ‘Miao’, speak: [Function] },可以看出是一个Pet对象。

用call或者apply关键字可以改变上下文环境。我们看下边这段代码。

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

这时的this就是dog对象,而不是pet对象了。

我们看看如何通过call来实现继承关系。

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