【问题标题】:How to I pass the object itself (like how we can do in C#) in mootools?如何在 mootools 中传递对象本身(就像我们在 C# 中可以做的那样)?
【发布时间】:2012-03-31 17:51:13
【问题描述】:

我想知道如何在 mootools 中将 self 传递给其他对象, 我正在尝试基于 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 都不起作用,有人可以指导我吗?

【问题讨论】:

    标签: c# javascript json mootools object-initializers


    【解决方案1】:
    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 的引用,则必须将该引用保存在变量中。

    【讨论】:

    • 当我在 firebug 和 Google Chrome 中签入时,我试过这是指 DOMWindow,即使我分配给 self 并通过 self 它仍然会指 DOMWindow 任何其他建议 Tomalak?
    • @Kathy 查看修改后的答案。我不确定您要将哪个对象传递给new Grass()var self = this; 在代码中的位置很大程度上是猜测。 做什么 Grass() 期望作为第一个参数?
    • Grass 期待已初始化的 World Class 我确实通过了 World,这没有运气,我尝试了您的建议,将其分配给 self 并通过 self,但没有运气:(
    • +1 - 这是要使用的正确模式。您也可以通过.bind(this) 来装饰函数,但保存引用更快且占用空间更小。
    • ...SelectMany(function(row) { ... return blah.Select(function(){ }.bind(this))}.bind(this)).toArray(); - function.bind 不是 mootools 特定的,它现在实际上是标准的:developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… - 这里不建议这样做,因为由于需要绑定 2 个函数,因此可读性会大大降低你可以虔诚地将this 绑定到实例...
    猜你喜欢
    • 2011-09-13
    • 1970-01-01
    • 2012-03-13
    • 2020-09-06
    • 2019-12-03
    • 2018-05-30
    • 1970-01-01
    • 2021-10-15
    • 2016-10-20
    相关资源
    最近更新 更多