首页 > 解决方案 > 构造函数方法以构造函数为参数并在Javascript中返回构造函数

问题描述

方法 sum 应该将另一个向量作为参数并返回一个新向量,该向量具有两个向量的总和(向量和参数的 x 和 y 值)。sum 的 return 语句给出错误,因此console.log(val3)返回 undefined。我该如何解决?

function Vector(a,b){
        this.x = a;
        this.y = b;
        this.sum = function(Vector){
            return Vector(this.x + Vector.x, this.y + Vector.y);
        }
    }
    Vector.prototype.show  = function(){
        document.write("x: "+this.x+" y: "+this.y);
        document.write("<br/>");
        document.write("Distance from Origin: " + Math.sqrt((this.x)**2 + (this.y)**2).toFixed(2));
    }
    var val1 = new Vector(5,6);
    var val3 = val1.sum(val2);
    console.log(val3);

标签: javascripthtmlobjectmethodsconstructor

解决方案


由于您正在实例化一个新对象,因此您需要使用new关键字。

new Vector(...)

另外,val2从未定义,所以我val3改为val2. 另外,当它们真正的意思是and时,不要使用aand 。bxy

function Vector(x, y) {
  this.x = x;
  this.y = y;
  this.sum = function(other) {
    return new Vector(this.x + other.x, this.y + other.y);
  }
}
Vector.prototype.show = function() {
  document.write("x: " + this.x + " y: " + this.y);
  document.write("<br/>");
  document.write("Distance from Origin: " + Math.sqrt((this.x) ** 2 + (this.y) ** 2).toFixed(2));
}
var val1 = new Vector(5, 6);
var val2 = val1.sum(val1);
console.log(val2);

您可以改用 ES5 类。

我建议您更改sumadd,除非您将多个向量添加在一起。并避免直接写入文档,除非您在框架内执行此操作。

class Vector {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  add(other) {
    return new Vector(this.x + other.x, this.y + other.y);
  }
  distanceTo(other) {
    return Math.sqrt((this.x - other.x) ** 2 + (this.y - other.y) ** 2);
  }
  distanceFromOrigin() {
    return this.distanceTo(new Vector(0, 0)); // Could make (0, 0) a singleton
  }
  display(el) {
    const htmlText = `
      x: ${this.x}, y: ${this.y}
      <br />
      Distance from Origin: ${this.distanceFromOrigin().toFixed(2)}
    `;
    if (el === undefined) {
      const p = document.createElement('p');
      p.innerHTML = htmlText;
      document.body.appendChild(p);
    } else {
      el.innerHTML = htmlText;
    }
  }
}
var val1 = new Vector(5, 6);
var val2 = val1.add(val1);
console.log(val2);
val2.display(document.querySelector('.info'));
<div class="info"></div>


推荐阅读