简体   繁体   English

Javascript-调用扩展功能时更改对象

[英]Javascript - Change Object when Extended Function called

I have a code like this: 我有这样的代码:

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);
    }
  }
};

This is how I then create it: 这就是我创建它的方式:

var MyVector = new Vector(32, 46);

Instead of this doing each time when I want to add to MyVector; 每次我要添加到MyVector时,都不必这样做;

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

I want to be able to do like this: 我希望能够这样做:

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

How do I make that possible? 我如何才能做到这一点?

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;
      }

    }
 }
}

Now you could just say: 现在您可以说:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM