使用 WinJS.Class 和访问属性

Using WinJS.Class and access properties

本文关键字:访问 属性 Class WinJS 使用      更新时间:2023-09-26

请看下面的代码:

(function() {
    "use strict";
    var game = WinJS.Class.define(
        null,
        {
            width: {
                get: function() {
                    return window.innerWidth;
                }
            },
            height: {
                get: function() {
                    return window.innerHeight;
                }
            },
            run: function() {
                // this.width and this.height is undefined
                Crafty.init(this.width, this.height);
                Crafty.canvas.init();
            }
        }
    );
    WinJS.Namespace.define("MyNamespace", {
        Game: new game()
    });
    window.addEventListener('load', MyNamespace.Game.run);
})();

我正在尝试访问run方法中的公共属性widthheight。我收到消息,this.width未定义。

如何访问它们?

最后我找到了解决方案。似乎WinJS.Namespace.define想要一个类定义而不是一个实例化的对象。我将代码更改为:

(function() {
    "use strict";
    var gameClass = WinJS.Class.define(
        null,
        {
            width: {
                get: function() {
                    return window.innerWidth;
                }
            },
            height: {
                get: function() {
                    return window.innerHeight;
                }
            },
            run: function() {
                // this.width and this.height is undefined
                Crafty.init(this.width, this.height);
                Crafty.canvas.init();
            }
        }
    );
    var game = new gameClass();
    WinJS.Namespace.define("MyNamespace", {
        Game: {
            get: function() {
                return game;
            }
        }
    });
    window.addEventListener('load', function() {
        MyNamespace.Game.run();
    });
})();

现在它正在工作:)