非常简单,我如何让我的示波器在这个例子中工作。范围日志的第一个引用到deck功能,但第二个引用到全局窗口。我如何使第二个参考甲板,就像我想要的那样。
谢谢!
http://jsbin.com/neqevo/1/edit?js
function Deck(){
this.suits = [ // this is an array now
{
'suit': 'diamonds',
'symbol': '♦',
'color': 'red'
}
]; // close suits
this.cardValues = [
{
'name': 'ace',
'face': 'A',
'value': 1
}
]; // close cardValues
this.cards = [];
console.log(this);
this.suits.forEach(function(currentSuit){
var scope = this;
console.log(scope);
// scope doesn't work.
// obviously, scope references window
// so how do i get it to refer to the deck like it's supposed to.
// i looked into using call and apply, and even though the concepts
// made sense i couldn't figure it out.
// fuck this is frustrating!
});
}
答案 0 :(得分:3)
在封闭函数中存储对this
的引用,并使用:
var me = this;
this.suits.forEach(function(currentSuit) {
console.log(me.suits);
});
或使用bind
:
this.suits.forEach(function(currentSuit) {
console.log(this.suits);
}.bind(this));
或者使用forEach
的第二个参数:(这可能是最佳解决方案。)
this.suits.forEach(function(currentSuit) {
console.log(this.suits);
}, this);
答案 1 :(得分:1)
你检查过它(?):
$this = this;
this.suits.forEach(function(currentSuit){
var scope = $this;
console.log(scope);
});
答案 2 :(得分:1)
首先将参考变量保存到卡座范围......
function Deck(){
var self = this; // save a reference to the deck context
this.suits = [ // this is an array now
{
'suit': 'diamonds',
'symbol': '♦',
'color': 'red'
}
]; // close suits
this.cardValues = [
{
'name': 'ace',
'face': 'A',
'value': 1
}
]; // close cardValues
this.cards = [];
console.log(this);
this.suits.forEach(function(currentSuit){
var scope = self;
console.log(scope);
// scope doesn't work.
// obviously, scope references window
// so how do i get it to refer to the deck like it's supposed to.
// i looked into using call and apply, and even though the concepts
// made sense i couldn't figure it out.
// fuck this is frustrating!
});
}
答案 3 :(得分:1)
解决此问题的一种方法是将“this”作为第二个参数传递给forEach。所以如果你编辑
this.suits.forEach(function(currentSuit){
var scope = this;
console.log(scope);
});
到
this.suits.forEach(function(currentSuit){
var scope = this;
console.log(scope);
}, this);
然后调用new Deck()将在两种情况下控制日志“Deck”。