A JavaScript question about objects

Status
Not open for further replies.

Defcon

Ars Tribunus Militum
2,039
Say I declare my 'class' like this :-

var Base = function(x) {
// private var
var local = x+1;

//private method
var test = function() {
....
}

//instance method in constructor
this.doStuff = function() {
...
}
}

// instance method using prototype
Base.prototype.doMore() = function() {...}

I know that doMore is the preferred way to add public instance methods (as long as they don't need access to private fields) because doMore's code is shared, doStuff's code is allocated for each object instance. And if I need to access private's, I can use what Crockford calls priveleged methods (which doStuff is).

What I'm not sure of - are local/test also shared, or ae they allocated for each object? Is there a good patter to determine what's being allocated per instance? In C++/C# I can do this by incrementing a class static id.

Sorry if this is trivial, am trying to learn JS :)
 
You should look into the concept of closures (plus prototyping), which would explain the behaviour you have described. Essentially, your 'private' members are simply part of the closure created with each instantiation. The prototype for all those instantiation would not have access to those closures, but can have additional members, which can be accessed by the instantiations through prototyping.
 
Status
Not open for further replies.