Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

best approach to member variables in object-oriented javascript?

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);
 }
}

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)};

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?

thanks,

-Morgan

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...