[英]Can someone explain working of this js code with reference to 'this' keyword?
JS代碼是:
this.sound1 ="global";
function cat(){
this.sound = 'meawo!!!!';
this.sound1 = 'meawooooo!!!!';
meawo1 = function(){
console.log(this.sound1);
console.log(this);
};
function meawo2(){
console.log(this.sound1);
console.log(this);
};
this.meawo = function(){
console.log(this.sound);
console.log(this);
meawo1();
meawo2();
};
};
var c = new cat();
c.meawo();
問:為什么this
里面meawo1
(函數表達式) meawo2
(函數表達式聲明)指的是“全球性”,而不是反對c
? 這是為什么?
一定要記住一個簡單的提示,同時想知道哪個對象不this
參考。
obj.method();
在上文中, method
的調用上obj
,因此this
在method
將它叫什么上,即obj = this
。
在你的情況下,雖然meowo
叫上c
, meowo1
和meowo2
不是對象你想要它來指代。
沒有明確的作用域的函數將被默認為全局上下文,盡管該函數本身不是全局的,並且由於閉包而可以利用其父上下文中的所有變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.