面向对象的javascript中成员变量的最佳方法? [英] best approach to member variables in object-oriented javascript?
问题描述
这是我刚刚发布的问题的后续跟进。
我想知道在使用MyClass.prototype定义方法时如何处理javascript clases中的成员变量。
This is a follow up to a question I just posted. I'm wondering how you all handle member variables in javascript clases when using MyClass.prototype to define methods.
如果你定义了所有的方法构造函数:
If you define all of the methods in the constructor function:
function MyClass(){
this.myMethod = function(){}
}
您可以很好地声明成员变量并从方法中访问它们:
You can very nicely declare member variables and access them from inside your methods:
function MyClass(){
var myVar = "hello";
this.myMethod = function(){
alert(myVar);
}
}
使用Object.prototype技术时,你会失去这个非常好,并且必须这样做;
When using the Object.prototype technique, you lose this nicety, and have to do it like this;
function MyClass(){}
MyClass.prototype.myVar = "hello";
MyClass.prototype.myMethod = function(){alert(this.hello)};
每次访问成员变量时,我都不会写this。我想使用Object.prototype方法出于内存和灵活性的原因,但在语法方面看起来很笨拙。这是你们一般的工作方式吗?
I'm not crazy about having to write "this" every time I access a member variable. I want to use the Object.prototype approach for memory and flexibility reasons, but it seems a lot clumsier syntax-wise. Is this how you folks generally work?
谢谢,
-Morgan
推荐答案
你应该克服使用这个
指针访问成员变量的厌恶。
You should get over your aversion to using the this
pointer to access member variables.
在构造函数中分配成员变量,您可以使用原型方法访问它们:
Assign member variables in the constructor, and you can access them with prototype methods:
function Cat(){
this.legs = 4;
this.temperament = 'Apathetic';
this.sound = 'Meow';
}
Cat.prototype.speak = function(){alert(this.sound)}
var cat = new Cat();
cat.speak();
是的,这些对象属性是公开的,但正如Guido所说,我们都是成年人。毕竟,Javascript是一种纯文本,松散类型的解释语言。在这种环境中私人变量的好处充其量是不稳定的。
Yes those object attributes are public but, as Guido would say, we're all adults here. Javascript is, after all, a plain-text, loosely-typed, interpreted language. The benefits of "private" variables in this environment are shaky at best.
我说只是明确而明确地说明如何访问您的对象,违规者将自行承担风险。
I say just be explicit and obvious about how your object should be accessed, and violators will stray from that at their own risk.
这篇关于面向对象的javascript中成员变量的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!