如果我在 JS 中有一个父对象,它有一个 block 保存到一个键,我如何在嵌套对象中调用它并正确引用“this”。
var colors = {
foo: function () {
return this.color;
},
red: {
color: 'red',
myColor: function () {
return foo();
}
},
blue: {
color: 'blue',
myColor: function () {
return foo();
}
}
};
这就是我所说的
colors.blue.myColor();
输出为
"blue"
我使用这个想法的确切上下文是
var accounts = {
checking: {
balance: 0,
deposit: function (amount) {
if (amount > 0) {
this.balance += amount;
}
},
withdraw: function (amount) {
var tA = accounts.totalAmount();
if (amount > 0 && amount <= this.balance) {
this.balance -= amount;
} else if (tA >= amount) {
accounts.savings.withdraw(amount - this.balance);
this.balance = 0;
}
}
},
savings: {
balance: 0,
deposit: function (amount) {
if (amount > 0) {
this.balance += amount;
}
},
withdraw: function (amount) {
var tA = accounts.totalAmount();
if (amount > 0 && amount <= this.balance) {
this.balance -= amount;
} else if (tA > amount) {
accounts.checking.withdraw(amount - this.balance);
this.balance = 0;
}
}
},
totalAmount: function() {
return accounts.savings.balance + accounts.checking.balance
}
};
我想在储蓄和支票之外提取存款功能,而是调用 block 。
最佳答案
您是否尝试过将值传递给 foo()?
var colors = {
foo: function (t) {
return t.color;
},
red: {
color: 'red',
myColor: function () {
return colors.foo(this);
}
},
blue: {
color: 'blue',
myColor: function () {
return colors.foo(this);
}
}
};
colors.blue.myColor();
关于javascript - 如何在 Javascript 中使用对此的新引用调用父定义的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26457729/