javascript - 构造函数方法以构造函数为参数并在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);
解决方案
由于您正在实例化一个新对象,因此您需要使用new
关键字。
new Vector(...)
另外,val2
从未定义,所以我val3
改为val2
. 另外,当它们真正的意思是and时,不要使用a
and 。b
x
y
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 类。
我建议您更改sum
为add
,除非您将多个向量添加在一起。并避免直接写入文档,除非您在框架内执行此操作。
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>
推荐阅读
- excel - 在 Excel VBA 中根据 2 个条件查找范围
- excel - 如何隐藏表格中的列而不隐藏包含表格的工作表上的列
- javascript - 即使使用 react 和 css 更改 div 中的内容,如何始终保持 div 中的分隔符与 div 的顶部箭头同步?
- python - TypeError:预期的 str、bytes 或 os.PathLike 对象,而不是 DecisionTreeClassifier 和 TypeError:Traceback(最近一次调用最后一次)
- php - Laravel 和 Vue 共享主机
- javascript - 模板表达式中缺少 }
- c++ - 如何调用函数内部的值?
- python - 在 tensorflow2.3.0 上急切执行
- python - 为什么使用 pyAesCrypt 加密文件时 pyqt5 gui 滞后
- c++ - 从屏幕上获取所有像素作为数组(C++,Windows)