0

我想知道如何将 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 有人可以指导我吗?

4

1 回答 1

2
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,则必须将该引用保存在变量中。

于 2012-03-15T08:23:15.667 回答