3

我正在尝试习惯 JavaScript (ECMAScript 5) 的“真正”原型继承,但不知何故,我的思绪似乎陷入了经典继承模式。

我想创建一个 Vector 对象,它执行简单的操作,例如加法、减法等。

现在有两种情况:

  • #1:将向量 B“添加到”向量 A(向量 A 被修改)
  • #2:将向量 B“添加到”向量 B(创建一个新的向量 C,它是 A 和 B 的总和)

在经典继承中,我会为场景 #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);

感谢您的任何建议!

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'
4

1 回答 1

2

Your Vector object is really just the prototype. You can use it with the Object.create function to create your Vector base/sub class. Then stick your static properties on your newly created Vector class. See here: 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​

Here is a good example of using Object.create with inheritance, static and instance properties. https://github.com/webadvanced/takeCommand/blob/master/src/takeCommand.module.js

于 2012-08-25T00:26:09.627 回答