What are the basic ways of defining reusable objects in Javascript? I say reusable to exclude singleton techniques, such as declaring a variable with object literal notation directly. I saw somewhere that Crockford defines four such ways in his book(s) but I would rather not have to buy a book for this short bit of information.
Here are the ways I'm familiar with:
Using this, and constructing with new (I think this is called classical?)
function Foo() {
var private = 3;
this.add = function(bar) { return private + bar; }
}
var myFoo = new Foo();
Using prototypes, which is similar
function Foo() {
var private = 3;
}
Foo.prototype.add = function(bar) { /* can't access private, correct? */ }
Returning a literal, not using this or new
function Foo() {
var private = 3;
var add = function(bar) { return private + bar; }
return {
add: add
};
}
var myFoo = Foo();
I can think of relatively minor variations on these that probably don't matter in any significant way. What styles am I missing? More importantly, what are the pros and cons of each? Is there a recommended one to stick to, or is it a matter of preference and a holy war?
Use the prototype. Returning specific objects from constructors makes them non-constructors, and assigning methods to this makes inheritance less convenient.
Returning an object literal
Pros:
If a person forgets new, they still get the object.
You can create truly private variables, since all methods of the object defined inside the constructor share its scope.
Cons:
It’s not a real constructor. Adding something to its prototype won’t change the returned objects, new or no new. new Foo() instanceof Foo would also result in false.
Using prototype
Pros:
You leave the constructor uncluttered.
This is the standard way of doing things in JavaScript, and all built-in constructors put their methods on their prototypes.
Inheritance becomes easier and more correct; you can (and should) use Object.create(ParentConstructor.prototype) instead of new ParentConstructor(), then call ParentConstructor from within Constructor. If you want to override a method, you’re able to do it on the prototype.
You can “modify” objects after they’ve already been created.
You can extend the prototypes of constructors you don’t have access to.
Cons:
It can get to be a bit too verbose, and if you want to change the function’s name, you have to change all of the functions added to the prototype, too. (Either that or define the prototype as one big object literal with a compatible property descriptor for constructor.)
They don’t share an instance-specific scope, so you can’t really have private variables.
Assigning to this.* in the constructor
Pros:
You can use closures and therefore private member variables.
Cons:
No duck typing; you can’t call a method right off of the prototype with any old object. For example, Array.prototype.slice.call(collectionLikeObject).
It's mostly a matter of preference. There's no one way to make Chicken Noodle soup, and uniform objects are the same way.
I don't use any of those 3, although they all work for their own purposes. I use a custom function called Object:deploy, and use it like this..
var a = { hey: 'hello' },
b = {}.deploy(a);
console.log(b.hey); // 'hello'
Using prototype is the best for most people because of automatic trickling.
function A() {};
A.prototype.hello = "Hey";
var a = new A();
console.log(a.hello); // 'Hey'
A.prototype.hello = "Hello";
console.log(a.hello); // 'Hello'
And contrary to popular belief, you can use private variables in prototype.
function Hello() {};
(function () {
var greeting = "Hello";
Hello.prototype.greet = function () { return greeting };
}).apply(this);
But even though that's possible, it's usually better to do..
function Hello() {};
Hello.prototype.greeting = "Hello";
Hello.prototype.greet = function () { return this.greeting };
Well the second approach (prototype) is more similar to standard classes in other languages like Python, in that you have a common "prototype" object which all instances are sharing. To compare the first and second approaches:
In approach 1, every time you call "new Foo()", you are creating a brand new object and inserting all the methods. This isn't very time or space efficient, since each Foo instance will have its own table of all the methods. You can test this by creating two Foo objects, and asking foo1.add == foo2.add (false). Approach 3 is very similar to this; I'm not sure what the semantic difference (if any) there is between approaches 1 and 3.
In approach 2, you have set up a shared prototype object containing all the methods. If you ask foo1.add == foo2.add, you get true. This is more space- and time-efficient. It also lets you add more methods to the prototype after creating instances, and they will see the new methods.
The problem with approach 2, as you say, is that you can't access the private members. But you can still add non-private members to the object itself, and access those using the prototype methods:
function Foo() {
this.private = 3;
}
Foo.prototype.add = function(bar) { return this.private + bar }
A caveat is that foo.private is visible externally.
The prototype one doesn't have a per object instance overhead only a per class overhead for the add function. This alone is the reason why I don't like the other two approaches.
Do not forget about inheritance. Some day you'll need. And for organizing inheritance the best approach is combined technic:
function Foo() {
this.array = [1, 2, 3];
this.add = function(bar) { return private + bar; }
}
Foo.prototype.add = function(bar) { }
var myFoo = new Foo();
Setting fields in constructor is useful to avoid modifying them by children objects.
Setting methods to prototype is faster then doing this every time in constructor.
Related
I've heard that one of the advantages of closures is the ability to create private properties for objects as follows.
function Func2(){
//A is a closure, kept alive after the Func2 has returned,
//After Func2 returns, A is only accessible by getA and setA (it's "private")
var A = 100;
return {
getA: function(){
return A;
},
setA: function(newA){
A = newA;
}
}
}
You can get and set the private property A of an object created with Func2 using the getter and setter functions...
var obj2 = Func2();
obj2.getA();
obj2.setA(200);
But what's the point of that if I can do the same thing using a regular constructor function?
function Func1(){
var A = 100; //A is a private property of any object created with the Func1 constructor
this.getA = function(){
return A;
};
this.setA = function(newA){
A = newA;
};
}
Accessing the private properties is done the same way...
var obj1 = new Func1()
obj1.getA();
obj1.setA(200);
As others have pointed out in the comments, a closure is created in both cases, and both will work.
I think the reason that the return approach is recommended for the module pattern is that the module pattern does not make use of Javascript's prototype chain, so it's unnecessary to use a regular constructor function that would create a new prototype (which isn't needed and would waste memory). In your example, objects created by Func2 would just have the default prototype of Object.prototype, whereas objects created by Func1 would have a prototype of Func1.prototype which in turn would have the prototype Object.prototype. Also, Func2 has the advantage that it will work with or without the new keyword (although it's best to avoid the new keyword if you're using the module pattern for the reasons I mentioned above). (I have seen some programmers complain about the fact that if a programmer forgets the new keyword in traditional OO Javascript, it can cause hard-to-detect bugs; I personally have never found this to be an issue though).
Another approach to private variables, as you're probably aware, is to simply prefix them with _, e.g.:
function Func1() {
this._A = 100;
}
Func1.prototype = {
constructor: Func1,
getA: function(){
return this._A;
},
setA: function(newA){
this._A = newA;
}
};
Personally I prefer this over the module pattern - the main goal of private variables is communication to other programmers, i.e. "this is an internal property; don't access it directly" - and the underscore prefix is a well-known convention. Private properties have never really been about 100% preventing access to those properties, just discouraging it (consider the fact that most programming languages allow you to access private properties using reflection if you really want to). And also, simply prefixing with an underscore allows you to easily have "protected" properties in addition to private ones (useful for sub-types / sub-classes). Making use of the prototype chain is also more memory-efficient, because you don't have multiple copies of the same functions for each instance.
But I do realize that in spite of the simplicity of the underscore naming convention, some programmers still prefer using the module pattern to really make private properties inaccessible from outside the closure. If you want to do that, then I'd recommend using the traditional module pattern, using the return statement as in your first example.
Another pattern you could consider, if you prefer to stick with the module pattern but still want to declare public properties as you go along (rather than in a return statement at the end), would be to create a new object and use that instead of this, e.g.:
function Func3(){
var obj = {};
var A = 100;
obj.getA = function(){
return A;
};
obj.setA = function(newA){
A = newA;
};
return obj;
}
(By the way, for private methods, as opposed to private data properties, the underscore prefix isn't a necessity even if you're using the prototypal approach. The code sample in this answer is an example of this.)
All, I found there are 3 ways to declare object in javascript.
var Waffle = {
tastes:'yummy'
};
var Waffle = function()
{
this.tastes='yummy';
};
function Waffle() {
var that = {};
that.tastes = "yummy";
return that;
}
The first way is Object literal it doesn't have a constructor.
I think the equal way to Object literal is below.
var Waffle = new Object();
Waffle.tastes = 'yummy';
(If my understanding is wrong. Please correct me.)
I want to know what the difference of these 3 ways is.
Which one is the best choice?
Thanks.
The literal notation and new Object() creates an object whose prototype is directly the Object. Also, properties and methods are attached on the instance.
/*
Object
A
| instance.__proto__
|
instance
*/
//all 3 yield the same result
var foo1 = {
bar : 'bam!'
}
var foo2 = {}
foo2.bar = 'bam!';
var foo3 = new Object();
foo3.bar = 'bam!';
The constructor approach, either the declared function or the assigned function expression approach, has an additional prototype level between the instance and the Object, which contains your prototype functions attached to the constructor's prototype. Anything attached to the constructor's prototype are shared across all instances.
/*
Object
A
| instance.__proto__.__proto__
|
constructor.prototype
A
| instance.__proto__
|
instance
*/
//these 2 are the same
//bar is attached at the instance
//function expression assigned to variable foo1
var foo1 = function(){
this.bar = 'bam!'
}
//function declaration named foo2
function foo2(){
this.bar = 'bam!'
}
//==========================================================================//
//these 2 are the same, but not the same as above
//methods live on the prototype level and are shared across instances
//function expression assigned to variable foo1
var foo1 = function(){}
//function declaration named foo2
function foo2(){}
foo1.prototype.bar = 'bam!'
foo2.prototype.bar = 'bam!'
The third approach returns a new literal. You don't get the benefits of the constructor method and prototype sharing. It's as if you just called Waffle like an ordinary function, created a literal, attached properties and methods, and returned it.
Best Choice: Depends on purpose.
Object literals:
Shorter than new Object and can attach methods/properties upon definition.
Properties/methods live on the instance, no running up the prototype chain which means faster look-up.
Unoptimized creation of objects might lead to duplicates, which waste memory. For example, creating functions per instance instead of sharing via the prototype.
Constructor:
Classical OOP style
Inheritance
Shared methods via the prototype means less memory used, as opposed to per instance methods.
Forgetting the new might have unwanted consequences, like attaching globals (if window is the context)
You can check these out in the Chrome Developer tools. Create them in the Console, and watch these expressions in the Sources tab
The first is an object literal and is the same as:
var Waffle = new Object();
Waffle.tastes = 'yummy';
which is the same as:
var Waffle = {};
Waffle.tastes = 'yummy';
but of course, their instantiations take multiple lines.
Your second and third examples are functions. Your second example is an expression, while your third example is a declaration. Here's an explanation of their differences: What is the difference between a function expression vs declaration in JavaScript?
Be careful with your second example (the expression), because in order to modify this (correctly), you need to use var waffle = new Waffle();. Since this is an expression, alternatively you could've used a declaration like:
function Waffle() {
this.tastes='yummy';
}
(to understand the main difference between that and the original, which I don't think affect many people ever, read the link I provided)
The third example is a basic function that returns a new object literal.
As for the best choice...I don't think there's a concrete, definite answer.
Your first example creates a simple, single object. You can add/change properties and methods on it. But it inherits directly from Object. I like to use this when I need one big object for holding many things, and its structure is static. To reuse this, your third example is needed.
Your second example is convenient because you can invoke a new instance, giving the effect of classic OOP...and is the one I normally use. Although the caveat is that you have to use new, otherwise the value of this will be window, which is bad. At the same time, you can modify this prototype and all instances will share it. It also gives you flexibility of having "private" variables, such as:
function Waffle() {
var testing = 0;
this.name = "A";
this.myMethod = function () {
return testing;
};
}
Your third example is similar to the second, except that you can't tap into a prototype, since you're returning an Object. It's basically using your first example, but making it reusable. It also allows for "private" variables like above, as well.
So if you're looking for a single object, use your first example. If you're looking for reusability, I'd suggest your second example, while the third is still an example. Hopefully I explained enough about each for you to determine which suits your needs.
All, I found there are 3 ways to declare object in javascript.
var Waffle = {
tastes:'yummy'
};
var Waffle = function()
{
this.tastes='yummy';
};
function Waffle() {
var that = {};
that.tastes = "yummy";
return that;
}
The first way is Object literal it doesn't have a constructor.
I think the equal way to Object literal is below.
var Waffle = new Object();
Waffle.tastes = 'yummy';
(If my understanding is wrong. Please correct me.)
I want to know what the difference of these 3 ways is.
Which one is the best choice?
Thanks.
The literal notation and new Object() creates an object whose prototype is directly the Object. Also, properties and methods are attached on the instance.
/*
Object
A
| instance.__proto__
|
instance
*/
//all 3 yield the same result
var foo1 = {
bar : 'bam!'
}
var foo2 = {}
foo2.bar = 'bam!';
var foo3 = new Object();
foo3.bar = 'bam!';
The constructor approach, either the declared function or the assigned function expression approach, has an additional prototype level between the instance and the Object, which contains your prototype functions attached to the constructor's prototype. Anything attached to the constructor's prototype are shared across all instances.
/*
Object
A
| instance.__proto__.__proto__
|
constructor.prototype
A
| instance.__proto__
|
instance
*/
//these 2 are the same
//bar is attached at the instance
//function expression assigned to variable foo1
var foo1 = function(){
this.bar = 'bam!'
}
//function declaration named foo2
function foo2(){
this.bar = 'bam!'
}
//==========================================================================//
//these 2 are the same, but not the same as above
//methods live on the prototype level and are shared across instances
//function expression assigned to variable foo1
var foo1 = function(){}
//function declaration named foo2
function foo2(){}
foo1.prototype.bar = 'bam!'
foo2.prototype.bar = 'bam!'
The third approach returns a new literal. You don't get the benefits of the constructor method and prototype sharing. It's as if you just called Waffle like an ordinary function, created a literal, attached properties and methods, and returned it.
Best Choice: Depends on purpose.
Object literals:
Shorter than new Object and can attach methods/properties upon definition.
Properties/methods live on the instance, no running up the prototype chain which means faster look-up.
Unoptimized creation of objects might lead to duplicates, which waste memory. For example, creating functions per instance instead of sharing via the prototype.
Constructor:
Classical OOP style
Inheritance
Shared methods via the prototype means less memory used, as opposed to per instance methods.
Forgetting the new might have unwanted consequences, like attaching globals (if window is the context)
You can check these out in the Chrome Developer tools. Create them in the Console, and watch these expressions in the Sources tab
The first is an object literal and is the same as:
var Waffle = new Object();
Waffle.tastes = 'yummy';
which is the same as:
var Waffle = {};
Waffle.tastes = 'yummy';
but of course, their instantiations take multiple lines.
Your second and third examples are functions. Your second example is an expression, while your third example is a declaration. Here's an explanation of their differences: What is the difference between a function expression vs declaration in JavaScript?
Be careful with your second example (the expression), because in order to modify this (correctly), you need to use var waffle = new Waffle();. Since this is an expression, alternatively you could've used a declaration like:
function Waffle() {
this.tastes='yummy';
}
(to understand the main difference between that and the original, which I don't think affect many people ever, read the link I provided)
The third example is a basic function that returns a new object literal.
As for the best choice...I don't think there's a concrete, definite answer.
Your first example creates a simple, single object. You can add/change properties and methods on it. But it inherits directly from Object. I like to use this when I need one big object for holding many things, and its structure is static. To reuse this, your third example is needed.
Your second example is convenient because you can invoke a new instance, giving the effect of classic OOP...and is the one I normally use. Although the caveat is that you have to use new, otherwise the value of this will be window, which is bad. At the same time, you can modify this prototype and all instances will share it. It also gives you flexibility of having "private" variables, such as:
function Waffle() {
var testing = 0;
this.name = "A";
this.myMethod = function () {
return testing;
};
}
Your third example is similar to the second, except that you can't tap into a prototype, since you're returning an Object. It's basically using your first example, but making it reusable. It also allows for "private" variables like above, as well.
So if you're looking for a single object, use your first example. If you're looking for reusability, I'd suggest your second example, while the third is still an example. Hopefully I explained enough about each for you to determine which suits your needs.
I'm just getting into JavaScript and I'm trying to wrap my head around prototypal inheritance. It appears that there's multiple ways to achieve the same effect, so I wanted to see if there is any best practices or reasons to do things one way over the other. Here's what I'm talking about:
// Method 1
function Rabbit() {
this.name = "Hoppy";
this.hop = function() {
console.log("I am hopping!");
}
}
// Method 2
function Rabbit() {}
Rabbit.prototype = {
name: "Hoppy",
hop: function() {
console.log("I am hopping!");
}
}
// Method 3
function Rabbit() {
this.name = "Hoppy";
}
Rabbit.prototype.hop = function() {
console.log("I am hopping!");
}
// Testing code (each method tested with others commented out)
var rabbit = new Rabbit();
console.log("rabbit.name = " + rabbit.name);
rabbit.hop();
All of these appear to have the same effect individually (unless I'm missing something). So is one method preferred over the other? How do you do it?
When you put a method on the prototype, every instance object shares the same reference to the method. If you have 10 instances, there is 1 copy of the method.
When you do what you did in example 1, every instance object has its own version of the same method, so if you create 10 of your objects, there are 10 copies of the code running around.
Using the prototype works because javascript has machinery for associated a function execution with a instance, i.e. it sets the this property for the execution of the function.
So using the prototype is highly preferred since it uses less space (unless of course, that is what you want).
In method 2, you are setting the prototype by setting it equal to an object literal. Note that here you are setting a property, which I think you don't intend to do, since all instances will get the same property.
In Method 3, you are building the prototype one assignment at a time.
I prefer method 3 for all things. i.e. In my constructor I set my property values
myObj = function(p1){
this.p1; // every instance will probably have its own value anyway.
}
myObj.prototype.method1 = function(){..} // all instances share the same method, but when invoked **this** has the right scope.
Let's look at your examples one at a time. First:
function Rabbit() {
this.name = "Hoppy";
this.hop = function() { //Every instance gets a copy of this method...
console.log("I am hopping!");
}
}
var rabbit = new Rabbit();
The above code will work, as you have said in your question. It will create a new instance of the Rabbit class. Every time you create an instance, a copy of the hop method will be stored in memory for that instance.
The second example looked like this:
function Rabbit() {}
Rabbit.prototype = {
name: "Hoppy",
hop: function() { //Now every instance shares this method :)
console.log("I am hopping!");
}
}
var rabbit = new Rabbit();
This time, every instance of Rabbit will share a copy of the hop method. That's much better as it uses less memory. However, every Rabbit will have the same name (assuming you don't shadow the name property in the constructor). This is because the method is inherited from the prototype. In JavaScript, when you try to access a property of an object, that property will first be searched for on the object itself. If it's not found there, we look at the prototype (and so on, up the prototype chain until we reach an object whose prototype property is null).
Your third example is pretty much the way I would do it. Methods shared between instances should be declared on the prototype. Properties like name, which you may well want to set in the constructor, can be declared on a per-instance basis:
function Rabbit(rabbitName) {
this.name = rabbitName;
}
Rabbit.prototype.hop = function() {
console.log("Hopping!");
}
This is an important issue that is often misunderstood. It depends what you're trying to do. Generally speaking, hvgotcode's answer is right on. Any object that will be instantiated frequently should attach methods and properties to the prototype.
But there are advantages to the others in very specific situations. Read this, including the comments: http://net.tutsplus.com/tutorials/javascript-ajax/stop-nesting-functions-but-not-all-of-them/
There are occasions when method 1 above helps, enabling you to have "private" readable/writable properties and methods. While this often isn't worth the sacrifice in heavily instantiated objects, for objects instantiated only once or a few times, or without many internal assignments, or if you're in a dev team environment with lots of different skill levels and sensibilities, it can be helpful.
Some devs incorporate another good strategy that attempts to bridge some of the shortcomings of the others. That is:
var Obj = function() {
var private_read_only = 'value';
return {
method1: function() {},
method2: function() {}
};
};
// option 4
var Rabbit {
constructor: function () {
this.name = "Hoppy";
return this;
},
hop: function() {
console.log("I am hopping!");
}
};
var rabbit = Object.create(Rabbit).constructor();
console.log("rabbit.name = " + rabbit.name);
rabbit.hop();
When doing prototypical OO using new and constructor functions is completely optional.
As has already been noted, if you can share something through the prototype do so. Prototypes are more efficient memory wise and they are cheaper in terms of instantiation time.
However a perfectly valid alternative would be
function Rabbit() {
// for some value of extend https://gist.github.com/1441105
var r = extend({}, Rabbit);
r.name = "Hoppy";
return r;
}
Here your extending "instances" with the properties of the "prototype". The only advantage real prototypical OO has is that it's a live link, meaning that changes to the prototype reflect to all instances.
Do some performance testing (declare around 1 milion rabbit variables) . First method will be the most time and memory consuming.
I've been playing around with prototypal inheritance after reading http://javascript.crockford.com/prototypal.html and having a bit of a problem with understanding how I could make use of it in the way I would use classical inheritance. Namely, all functions and variables inherited by the prototype essentially become statics unless they are overwritten by the child object. Consider this snippet:
var Depot = {
stockpile : [],
loadAmmo : function (ammoType) {
this.stockpile.push(ammoType);
}
};
var MissileDepot = Object.create(Depot);
var GunDepot = Object.create(Depot);
stockpile and loadAmmo definitely should be in the prototype, since both MissileDepot and GunDepot have them. Then we run:
MissileDepot.loadAmmo("ICBM");
MissileDepot.loadAmmo("Photon Torpedo");
alert(MissileDepot.stockpile); // outputs "ICBM,Photon Torpedo"
alert(GunDepot.stockpile); // outputs "ICBM,Photon Torpedo"
This is expected because Neither MissileDepot nor GunDepot actually have stockpile or loadAmmo in their objects, so javascript looks up the inheritance chain to their common ancestor.
Of course I could set GunDepot's stockpile manually and as expected, the interpreter no longer needs to look up the chain
GunDepot.stockpile = ["Super Nailgun", "Boomstick"];
alert(GunDepot.stockpile); // outputs "Super Nailgun,Boomstick"
But this is not what I want. If this were classical inheritance (say Java), loadAmmo would operate on MissileDepot and GunDepot's stockpile independently, as an instance method and an instance variable. I would like my prototype to declare stuff that's common to children, not shared by them.
So perhaps I'm completely misunderstanding the design principles behind prototypal inheritance, but I'm at a loss as how to achieve what I've just described. Any tips? Thanks in advance!
Javascript provides a way to do this the way U are used to :)
try this:
function Depot() {
this.stockpile = [],
this.loadAmmo = function (ammoType) {
this.stockpile.push(ammoType);
}
};
var MissileDepot = new Depot();
var GunDepot = new Depot();
MissileDepot.loadAmmo("ICBM");
MissileDepot.loadAmmo("Photon Torpedo");
alert(MissileDepot.stockpile); // outputs "ICBM,Photon Torpedo"
alert(GunDepot.stockpile); // outputs ""
And U can add the functions on the fly afterwards:
MissileDepot.blow = function(){alert('kaboom');}
Extending object with another object is also an option, but what You wanted is the fact, that OO programming in javascript is done by functions not objects with {} ;)
EDIT:
I feel bad for writing that without mentioning: The javascript "new" keyword is only for making it easier to OO veterans. Please, dig deeper into the prototypal inheritance and dynamic object creation as therein lies true magic! :)
For the method, all works as expected. It's just the fields that you need to take care of.
What I see a lot in YUI, is that the constructor allocates the instance varialbes. 'Classes' that inherit from a parent call the constructor of their parent. Look here:
http://developer.yahoo.com/yui/docs/DataSource.js.html
Example base class:
util.DataSourceBase = function(oLiveData, oConfigs) {
...
this.liveData = oLiveData;
... more initialization...
}
Example subclass:
util.FunctionDataSource = function(oLiveData, oConfigs) {
this.dataType = DS.TYPE_JSFUNCTION;
oLiveData = oLiveData || function() {};
util.FunctionDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
};
// FunctionDataSource extends DataSourceBase
lang.extend(util.FunctionDataSource, util.DataSourceBase, {
...prototype of the subclass...
});
To achieve what you want, you need a cloning method. You don't want an inheritance prototype, you want a cloning prototype. Take a look at one of the Object.clone() functions already implemented, like prototypejs's one: http://api.prototypejs.org/language/object.html#clone-class_method
If you want to stick to some kind of prototyping, you have to implement an initialize() method that will give a stockpile property to your newly created Depots. That is the way prototypejs Classes are defined : a cloned prototype and an initialize() method : http://prototypejs.org/learn/class-inheritance
That's because you're trying to make a cat meow! Douglas Crockford is good, but that script you're using essentially works by looping through your parent object and copying all of its attributes into the prototype chain--which is not what you want. When you put things in the prototype chain, they're shared by all instances of that object--ideal for member functions, not ideal for data members, since you want each object instance to have its own collection of data members.
John Resig wrote a small script for simulating classical inheritance. You might want to check that out.
The secret to instance variables in JavaScript is that they are shared across methods defined in superclasses or from included modules. The language itself doesn't provide such a feature, and it may not be possible to mesh with Prototypal inheritance because each instance will need it's own instance variable capsule, but by using discipline and convention it is fairly straightforward to implement.
// Class Depot
function Depot(I) {
// JavaScript instance variables
I = I || {};
// Initialize default values
Object.reverseMerge(I, {
stockpile: []
});
return {
// Public loadAmmo method
loadAmmo: function(ammoType) {
I.stockpile.push(ammoType);
},
// Public getter for stockpile
stockpile: function() {
return I.stockpile;
}
};
}
// Create a couple of Depot instances
var missileDepot = Depot();
var gunDepot = Depot();
missileDepot.loadAmmo("ICBM");
missileDepot.loadAmmo("Photon Torpedo");
alert(missileDepot.stockpile()); // outputs "ICBM,Photon Torpedo"
alert(gunDepot.stockpile()); // outputs ""
// Class NonWeaponDepot
function NonWeaponDepot(I) {
I = I || {};
// Private method
function nonWeapon(ammoType) {
// returns true or false based on ammoType
}
// Make NonWeaponDepot a subclass of Depot and inherit it's methods
// Note how we pass in `I` to have shared instance variables
return Object.extend(Depot(I), {
loadAmmo: function(ammoType) {
if(nonWeapon(ammoType)) {
// Here I.stockpile is the same reference an in the Depot superclass
I.stockpile.push(ammoType);
}
}
});
}
var nonWeaponDepot = NonWeaponDepot();
nonWeaponDepot.loadAmmo("Nuclear Bombs");
alert(nonWeaponDepot.stockpile()); // outputs ""
And that's how to do instance variables in JavaScript. Another instance variable example using the same technique.