我正在尝试习惯JavaScript的“真实”原型继承(ECMAScript 5),但不知怎的,我的思想似乎陷入了经典的继承模式。
我想创建一个Vector对象,它执行简单的操作,如添加,减去等。
现在有两种情况:
在经典继承中,我将为场景#1创建一个实例方法,为场景#2创建一个静态方法,但似乎原型继承中没有静态函数。
那么,实现这两种情况的干净方法是什么?
这是我到目前为止所得到的:
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);
感谢您的任何建议!
更新:
这是我尝试使用Paul的建议实现静态函数(谢谢!):
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'
答案 0 :(得分:2)
您的Vector
对象实际上只是原型。您可以将其与Object.create
函数一起使用来创建Vector
基础/子类。然后将静态属性粘贴到新创建的Vector
类上。见这里:http://jsfiddle.net/agYNc/1/
var vectorPrototype = {
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);
}
};
//create your base Vector type
var Vector = Object.create( vectorPrototype );
//Your static functions here
Vector.staticFunction = function ( vec1, vec2 ) {};
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
这是使用Object.create
继承,静态和实例属性的一个很好的例子。 https://github.com/webadvanced/takeCommand/blob/master/src/takeCommand.module.js