I’m trying to get used to the “real” prototypal inheritance of JavaScript (ECMAScript 5) but somehow my mind seems to be stuck in the classical inheritance pattern.
I’d like to create a Vector object which performs simple operations such as adding, subtracting etc.
Now there are two scenarios:
- #1: Adding Vector B “to” Vector A (Vector A gets modified)
- #2: Adding Vector B “to” Vector B (a new Vector C is created, which is the sum of A and B)
In classical inheritance I’d create an instance method for scenario #1 and a static method for case #2 but it seems like there are no static functions in prototypal inheritance.
So, what’s a clean way to realize these two scenarios?
Here’s what I’ve got so far:
var Vector = {
x: 0,
y: 0,
z: 0,
initialize: function(x,y,z) {
this.x = x;
this.y = y;
this.z = z;
return this;
},
add: function(vec) {
this.x += vec.x;
this.y += vec.y;
this.z += vec.z;
return this;
},
print: function() {
console.log('x:', this.x, 'y:', this.y, 'z:', this.z);
}
};
var firstVector = Object.create(Vector).initialize(1,2,3);
var secondVector = Object.create(Vector).initialize(4,5,6);
firstVector.print(); // Outputs: x:1, y:2, z:3
secondVector.print(); // Outputs: x:4, y:5, z:6
firstVector.add(secondVector);
firstVector.print(); // Outputs: x:5,y:7,z:9
// What I'm looking for:
var thirdVector = Vector.add(firstVector, secondVector);
Thanks for any advice!
Update:
Here is my attempt to implement a static function using Paul’s advice (thanks!):
var vectorPrototype = {
hello: function() { console.log('hello I am the prototype'); }
};
var Vector = Object.create(vectorPrototype);
Vector.hello = function() { console.log('hello I am the static function'); };
Vector.init = function() {
return Object.create(vectorPrototype);
}
var vec1 = Vector.init();
vec1.hello(); // says: 'hello I am the prototype'
Vector.hello(); // says: 'hello I am the static function'
Your
Vectorobject is really just the prototype. You can use it with theObject.createfunction to create yourVectorbase/sub class. Then stick your static properties on your newly createdVectorclass. See here: http://jsfiddle.net/agYNc/1/Here is a good example of using
Object.createwith inheritance, static and instance properties. https://github.com/webadvanced/takeCommand/blob/master/src/takeCommand.module.js