我想知道如何将 self 传递给 mootools 中的另一个对象, 我正在尝试基于 mootools 类声明构建类,但我注意到我无法使用它发送对象本身,当我使用它时,它发送 DOMWindow 而不是 World 或对象本身,以下是我的代码,
var World = new Class({
....
initialize: function(rows, ...) {
// build grass // can only have one grass per location
this.grassList = Enumerable.Range(0, rows).SelectMany(
function(row) {
return Enumerable.Range(0, columns).Select(
function(column) {
return new Grass(this, new Location(row, column), quantityOfGrass, maxQuantityOfGrass, growRateOfGrass)
})
}).ToArray();
}
....
}
我在此位置遇到问题,
return new Grass(this, new Location(row, column), quantityOfGrass, maxQuantityOfGrass, growRateOfGrass)
因为它不起作用,我检查了一下,
return new Grass(World, new Location(row, column), quantityOfGrass, maxQuantityOfGrass, growRateOfGrass)
我使用 linq.js 和 mootools 都不起作用,有人可以指导我吗?
最佳答案
var World = new Class({
....
initialize: function(rows, ...) {
// save a reference to the correct "this"
var self = this;
// build grass // can only have one grass per location
self.grassList = Enumerable.Range(0, rows).SelectMany(
function(row) {
return Enumerable.Range(0, columns).Select(
function(column) {
return new Grass(self, new Location(row, column), quantityOfGrass, maxQuantityOfGrass, growRateOfGrass)
})
}).ToArray();
}
....
}
this
引用的对象动态变化。
像 function(column)
这样的回调函数将不知道 this
在之前调用的函数中引用的内容。如果您想重复使用对特定 this
的引用,则必须将该引用保存在变量中。
关于c# - 如何在 mootools 中传递对象本身(就像我们在 C# 中所做的那样)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9716052/