function函數(shù)調用中經(jīng)常用到this ,
但是this具體是指的什么 ,它的作用范圍還是不太清楚
今天在慕課聽nodejs 課程的時候老師講了一下 不同函數(shù)中this的所指
下面直接上代碼
1.作為對象方法的調用
這時this就指這個上級對象。
?var pet = {
? ?words:'...',
? ?speak:function(){
? ? ? console.log(this.words)
? ? ? ?console.log(this ===pet)
? ? ?}
?}
?pet.speak();
node 在終端運行的時候打印出
//...
//true
說明此時的this 指的是調用的函數(shù)對象,該函數(shù)對象是speak函數(shù)所在的pet
2.this指向全局對象
這是函數(shù)的最通常用法,屬于全局性調用,因此this就代表全局對象Global。
?function pet(words){
? ?this.words = words
? ?console.log(this.words)
? ? console.log(this===global)
?}
pet('...');
//...
//true
var x=1;
function text(){
? ? ?alert(this.x)
}
text();//1
.........................................
var ?x=1;
function test(){
? ?this.x =0;
}
test();
alert(x);
3.作為構造函數(shù)調用
所謂構造函數(shù),就是通過這個函數(shù)生成一個新對象(object)。這時,this就指這個新對象。
function Pet(words){
? ? ?this.words=words
? ? ?this.speak=function(){
? ? ? ? ? console.log(this.words)
? ? ? ? ? console.log(this)
? ? ?}
?}
var cat = new Pet('miao')
cat.speak();
//miao
// Pet{word:'miao',speak:[function]}