javascript - 这个模块片段有什么问题?

标签 javascript module-pattern

我想在对象中拥有私有(private)属性。以下代码不起作用:

var GameModule = (function(ns){

    function Game(ctx) {
        var self   = this, //use self in callback methods (requestAnimationFrame etc)
            ctx    = ctx,

        var dx = 1,
            dy = 1;

        console.log(dx, dy); //writes 1,1,

        console.log(self.dx, self.dy); //writes undefined, undefined
    }

    ns.Game = Game;
    return ns;

})(GameModule || {});

//somewhere later in a different file
$(document).ready(function(){
   var game = new GameModule.Game(some_ctx);
});

看起来 vars 类似于静态成员,而不是私有(private)成员。

我是否必须编写 this.dx = 1 以使变量可访问(例如在成员函数中)?它不会使变量公开吗?

最佳答案

要在 Javascript 中定义类属性,您可以这样做(Fiddle):

var Class = function(){

    this.property = 'now this is a property';

    Class.staticProperty = 'and this is a static property';

    var property = 'this is NOT a property, but a local variable';
};

Class.prototype.propertyToo = 'this is also a property';

var object = new Class();

console.log(object.property);
console.log(object.propertyToo);
console.log(Class.staticProperty);

JavaScript 语言本身没有提供任何访问修饰符,所以没有tricky methods 就不能实现私有(private)属性。 .

关于javascript - 这个模块片段有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14592951/

相关文章:

php - Javascript/Cookie 是启用还是禁用?

javascript - 了解在 JavaScript 中以模块模式命名返回对象的好处

javascript - 继承和模块模式

javascript - 模块模式 : Restrict a module from being extended

javascript - 使用 browserify 时闭包/模块模式是否已过时?

javascript - 用于 TypeScript : Class or Interface? 中的纯数据对象的内容

javascript - Android:如何在点击时启动系统放大镜

javascript - 如何一次从多个表中获取书架模型

javascript - 后退按钮、Chrome 和 DOM 更新存在严重问题

javascript - 模块模式-如何将一个模块的代码拆分到不同的js文件中?