2017-04-25 75 views
0

爲什麼7行返回對象窗口爲什麼這樣的背景?

爲什麼不是運動對象?

var sport = { 
caption: "2017", 
players : [{"name":"cat"},{"name":"dog"}] , 
show: function() { 
    this.players.forEach(function(entry) { 
     console.log(entry.name); 
     console.log(this);//window 
    }); 
} 
} 

sport.show(); 

https://jsfiddle.net/6qkj2byk/

+2

使用箭頭功能。 –

+2

這個範圍取決於執行上下文,並且是遲到的。搜索SO和網絡,你會發現很多關於這個問題的討論。 –

+2

「如果給forEach()提供了thisArg參數,它將被用作回調函數的這個值,否則undefined值將被用作它的這個值,這個最終可以被回調觀察到的值是根據通常的規則確定一個函數看到的這一點。「 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach – Nayuki

回答

1

this是指它在其中駐留的匿名功能,這將是窗口的範圍。

var sport = { 
 
    players: [1, 2, 3], 
 
    show: function() { 
 
    this.players.forEach(function(entry) { 
 
     console.log(entry); 
 
     
 
     // this refers to the scope of the anonymous function, which is window 
 
     console.log(this); 
 
    }); 
 
    } 
 
} 
 

 
//sport.show(); 
 

 

 
var sport2 = { 
 
    players: [3, 4, 5], 
 
    show: function() { 
 

 
    // this refers to the object scope in which it resides - 
 
    // in which case, that would be "sport2" 
 
    var self = this; 
 
    this.players.forEach(function(entry) { 
 
     console.log(entry); 
 

 
     // self is now synonymous with "this" in the sport2 scope. 
 
     console.log(self); 
 
    }); 
 
    } 
 
} 
 

 
sport2.show();

編輯:自可以在show功能本身的內部設置,沒有必要將它傳遞的醜陋的方式。感謝評論部分指出了這一點。

+0

爲什麼downvote? –

+0

因爲'this'幾乎*從不*指代一個函數 – Bergi

+0

建議:在函數內你可以定義'var self = this;' – Nayuki