Javascript 中的构造函数不会返回由原型函数传递的正确值

Constructer in Javascript does not return correct value that is passed by prototype function

本文关键字:函数 原型 构造函数 返回 Javascript      更新时间:2023-09-26

我用构造函数 Vector(它有两个参数)编写了一段代码,我希望通过原型函数传递不同的参数集,并希望汇总两组参数的值。

但是我在打印最终矢量时遇到了问题。

function Vector(x, y) {
    this.x = x;
    this.y = y;
    console.log(x, y);//initially this prints (3,3)
    return (x, y);
}

Vector.prototype.plus = function (a, b) {
    this.x = this.x + a;
    this.y = this.y + b;
    console.log(this.x, this.y);// After passing (1,9) it prints (4,12)but      
     return (this.x, this.y);   //after returning (this.x, this.y) it   
                                //prints only Y coordinate as 12
}
var type_vector = new Vector(3, 3);
console.log(type_vector.plus(1, 9));

输出:(3,3),(4,12),12

我相信

你来自python背景,因为那里(x,y)作为元组返回。在JS中,如果您返回(x,y);它将是右括号处的值(在本例中为 y)。您必须为目标使用对象或数组。

在控制台上尝试此操作:

var a = (3, 4, 5, 6);
console.log(a);

好吧,在 JavaScript 中,如果你想返回一个数组,你可以使用 [] 表示法。

与您的版本不同:

function Vector(x, y) {
  this.x = x;
  this.y = y;
  console.log(x, y);
  return this;
}
Vector.prototype.plus = function(a, b) {
  this.x = this.x + a;
  this.y = this.y + b;
  console.log(this.x, this.y);
  return [this.x, this.y];
};
var type_vector = new Vector(3, 3);
console.log(type_vector.plus(1, 9));