Javascript 原型遗传与静态方法
我试图习惯JavaScript(ECMAScript 5)的“真实”原型继承,但不知何故,我的思维似乎陷入了经典继承模式 我想创建一个向量对象,它执行简单的操作,比如加法、减法等 现在有两种情况:Javascript 原型遗传与静态方法,javascript,static-methods,ecmascript-5,prototypal-inheritance,Javascript,Static Methods,Ecmascript 5,Prototypal Inheritance,我试图习惯JavaScript(ECMAScript 5)的“真实”原型继承,但不知何故,我的思维似乎陷入了经典继承模式 我想创建一个向量对象,它执行简单的操作,比如加法、减法等 现在有两种情况: #1:将向量B“添加”到向量A(向量A被修改) #2:将向量B“添加”到向量B(创建一个新的向量C,它是a和B的总和) 在经典继承中,我会为场景#1创建一个实例方法,为案例#2创建一个静态方法,但在原型继承中似乎没有静态函数 那么,实现这两个场景的干净方法是什么 以下是到目前为止我得到的信息: v
- #1:将向量B“添加”到向量A(向量A被修改)
- #2:将向量B“添加”到向量B(创建一个新的向量C,它是a和B的总和)
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的建议实现静态函数的尝试(谢谢!)
你的
向量
对象实际上就是原型。您可以将它与对象一起使用。create
函数创建向量
基类/子类。然后将静态属性粘贴到新创建的Vector
类上。请看这里:
下面是一个使用
对象的好例子。创建带有继承、静态和实例属性的 您好,非常感谢您的建议和链接!我试着实现一个静态函数(见我问题中的更新),这是“正确”的方法吗?在类似的情况下,我的静态方法已经连接到“原型”(vectorPrototype)上了。我可以将它继承到子类(Vector)上吗?还是应该在我的子类中定义它?谢谢
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'
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