代码之家  ›  专栏  ›  技术社区  ›  devamat

Javascript:类中的绑定长度

  •  1
  • devamat  · 技术社区  · 6 年前

    我从一本书上解决了这个练习,但我有问题(如下)。

    给Vec原型两种方法,plus和minus,将另一个向量作为参数,并返回一个新的向量,该向量具有两个向量(this和参数)x和y值的和或差。

    将getter属性length添加到计算向量长度的原型,即点(x,y)到原点(0,0)的距离。

    // Your code here.
    
    console.log(new Vec(1, 2).plus(new Vec(2, 3)));
    // → Vec{x: 3, y: 5}
    console.log(new Vec(1, 2).minus(new Vec(2, 3)));
    // → Vec{x: -1, y: -1}
    console.log(new Vec(3, 4).length);
    // → 5
    

    class Vec {
        constructor(x, y) {
            this.x = x;
            this.y = y;
            length = Math.sqrt(this.x * this.x + this.y * this.y);
            }
        plus(v) {
            return { x: this.x + v.x, y: this.y + v.y };
        }
        minus(v) {
            return { x: this.x - v.x, y: this.y - v.y };
        }
    
    }
    
    console.log(new Vec(1, 2).plus(new Vec(2, 3)));
    // → Vec{x: 3, y: 5}
    console.log(new Vec(1, 2).minus(new Vec(2, 3)));
    // → Vec{x: -1, y: -1}
    console.log(new Vec(3, 4).length);
    // → 5
    

    这是可行的,但我想改进我的解决方案。如果我改变向量的x或y的值,长度值将是错误的,因为它是在构造函数中计算的。例子:

    let vecTest = new Vec(3, 4);
    
    console.log(vecTest.length);
    // → 5 (this value is ok)
    
    vecTest.x -= 3;
    // the value of x has now changed, but the lenght value has not!
    
    console.log(vecTest.length);
    // → 5 (this value is NOT ok)
    
    console.log(Math.sqrt(vecTest.x * vecTest.x + vecTest.y * vecTest.y));
    // → 4 (this is what the value should be)
    

    我知道我可以用一个函数来实现这一点,但是有没有一种方法可以只用绑定来实现呢?我试着用这样的原型:

    Vec.prototype.length = Math.sqrt(this.x * this.x + this.y * this.y);
    

    我在类外设置了这个值,但它不起作用。”这“事实上是没有定义的。

    有什么建议吗?谢谢。

    1 回复  |  直到 4 年前
        1
  •  5
  •   Ram    6 年前

    你可以使用 getter 对于 .length 属性:

    class Vec {
        constructor(x, y) {
            this.x = x || 0;
            this.y = y || 0;
        }
        get length() {
          return Math.sqrt(this.x * this.x + this.y * this.y);
        }
        // ...
    }
    

    这个 实例的属性成为动态计算的值。

    .plus .minus 函数是可链接的,而不是返回对象文本。

    plus(v) {
        this.x += v.x
        this.y += v.y;
        return this;
    }
    minus(v) {
        this.x -= v.x
        this.y -= v.y;
        return this;
    }
    

    new Vec(...).plus(...).plus(...).minus(...).length .

        2
  •  0
  •   Full Life    4 年前
    class Vec {
      constructor(a,b){
        this.a = a;
        this.b = b;
      }
      plus(c){
        return `Vec{x : ${this.a + this.b}, y : ${c.a + c.b} }`;
      }
      minus(c){
        return `Vec{x : ${this.a - this.b}, y : ${c.a - c.b} }`;
      }
      length(){
        return Math.sqrt(Math.pow(this.a,2) + Math.pow(this.b,2));
      } 
    }
    
    
    console.log(new Vec(1, 2).plus(new Vec(2, 3)));
    // → Vec{x: 3, y: 5}
    console.log(new Vec(1, 2).minus(new Vec(2, 3)));
    // → Vec{x: -1, y: -1}
    console.log(new Vec(3, 4).length());
    // → 5`