1

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

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类似于静态成员,而不是私有成员。

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

4

3 回答 3

1

要在 Javascript 中定义类属性,你可以这样做(小提琴):

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 语言本身并没有提供任何访问修饰符,因此没有棘手的方法就无法完成私有属性。

于 2013-01-29T22:14:47.163 回答
1

您创建的模块中有几个错误。首先,dx当用 定义时是一个私有变量var dx。它可以在函数内部访问,但不能在外部访问,除非通过 return 语句公开,这将使其伪公开。

但是,我相信您错过了一个关键区别。有两种类型的功能。一个可以被调用的函数,例如function func(){}一个函数对象,当new关键字被发送给一个函数时,将它变成一个函数对象,比如new func();,或者在你的例子中new GameModule.Game(some_ctx);

一旦Gamenew关键字、Gameis aFunction Object和 is an实例化instanceof Game。此时,可以使用this关键字将变量或函数附加到函数对象。在 a 的内部Function Objectthis是指对象,而在 a 的外部是Function Object this指窗口。您不能使用var this.variableName,因为那不是有效的语法。您不是在创建变量,而是在扩展对象。因此,var dxthis.dx是内存中的两个不同位置,具有不同的值。

我希望这能为你澄清一些。

这是一个演示:http: //jsfiddle.net/BCZKG/

js:

var GameModule = (function(ns){

    function Game(ctx) {
        var self = this,
        ctx = ctx,
        dx = 1,
        dy = 1;
        self.dx = 2,
        self.dy = 2;

        console.log(dx, dy);//1 1
        console.log(self.dx, self.dy);//2 2
    }

    ns.Game = Game;
    return ns;
})(GameModule || {});

var some_ctx = {};
var game = new GameModule.Game(some_ctx);
于 2013-01-29T22:16:37.630 回答
0

我不确定实际问题是什么,但我看到的一个问题是您没有执行 Game by:

ns.Game = Game();

但是要使 var 在对象外部可访问,您必须执行 this.dx 或使用 return 语句,如:

return {
  dx: dx,
  dy: dy
}

这是你想要的?

于 2013-01-29T22:14:48.917 回答