Javascript 中的构造函数不会返回由原型函数传递的正确值
Constructer in Javascript does not return correct value that is passed by prototype function
我用构造函数 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));
相关文章:
- 创建对象函数原型和代码是错误的
- 使用sinon.js创建一个“;“间谍对象”;使用基于真实构造函数/原型的间谍方法
- 使用构造函数 - 原型从文本框输出值
- 为什么函数对象的实例没有继承函数原型属性
- 获取函数原型的源代码
- 挂钩文档.使用函数原型创建元素
- 理解函数原型和__proto__
- 在Javascript的函数原型中创建函数
- Emberjs :哈希中的函数原型
- Javascript函数在父函数原型中带有原型
- 构造函数原型-继承混淆
- 本地作用域函数原型覆盖
- 使用函数原型的 JavaScript 继承问题
- 为什么我的代码认为 canvas 函数在 JavaScript 中的构造函数原型中是未定义的
- 所有内容也都链接到函数原型
- Javascript MDN 函数原型绑定 polyfill 在数组中是可枚举的
- Javascript将对象传递给函数原型
- 我应该使用构造函数/原型吗?
- 为什么函数原型不能修改 .
- 删除函数原型对象