我想在对象中拥有私有(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/