Javascript - 调用扩展函数时更改对象

时间:2014-04-12 06:59:58

标签: javascript function object

我有这样的代码:

var Vec = function(x, y) {
  this.x = x || 0;
  this.y = y || 0;
};

Vec.prototype = {
  set: function(v) {
    this.v.x = v.x;
    this.v.y = v.y;

    return this;
  },

  add: function(add) {
    if (add instanceof Vec) {
      return new Vec(this.v.x + add.x, this.v.y + add.y);
    } else {
      return new Vec(this.v.x + add, this.v.y + add);
    }
  }
};

这就是我创建它的方式:

var MyVector = new Vector(32, 46);

每当我想要添加到MyVector时,而不是这样做;

MyVector.set(MyVector.add(new Vec(12, 7))); // MyVector = MyVector.add(new Vec(12, 7)); Same thing

我希望能够这样做:

MyVector.add(new Vec(12, 7)).set();

我该如何做到这一点?

1 个答案:

答案 0 :(得分:0)

var Vec = function(a,b) {
  return {
     x: a,
     y: b,

     set: function(vector) {
       this.x = vector.x;
       this.y = vector.y;
     },

     get: function() {
       return {x: this.x, y:this.y};
     },       

    add: function(v) {
      if(s.constructor === new Vec().constructor) {
        values = v.get();
        this.x += values.x;
        this.y += values.y;
      } 
      else {
        this.x += v;
        this.y += v;
      }

    }
 }
}

现在你可以说:

 var v = new Vec(12,13);
 v.add(new Vect(14,15));