我正在创建一个Vector类,它基本上可以容纳三个数值。然而,可以对这样的向量执行许多操作-例如,获取幅值,添加或减去另一个向量等。
我想知道这些函数是应该编码为Vector类的原型函数,还是应该在构造函数中定义它们。
那么这两种方法中哪一种更可取呢?
function Vector3D(x, y, z) {
this.x = x;
this.y = y
this.z = z;
}
Vector3D.prototype.magnitude = function() {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
};
或
function Vector3D(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
this.magnitude = function() {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
};
}
发布于 2011-01-14 20:33:53
原型化方法仅适用于公共属性,如果您将x,y,z作为“私有”变量来跟踪,则原型将无法工作。
我会使用后者,因为您可能需要只使用私有/内部变量的方法,但这完全取决于上下文。
function Vector3D(x, y, z) {
// x, y, z is automatically in this scope now, but as private members.
this.magnitude = function() {
return Math.sqrt(x * x + y * y + z *z);
}
}
发布于 2017-02-22 21:24:37
ECMA 6 http://es6-features.org/#BaseClassAccess
class Shape {
…
toString () {
return `Shape(${this.id})`
}
}
class Rectangle extends Shape {
constructor (id, x, y, width, height) {
super(id, x, y)
…
}
toString () {
return "Rectangle > " + super.toString()
}
}
class Circle extends Shape {
constructor (id, x, y, radius) {
super(id, x, y)
…
}
toString () {
return "Circle > " + super.toString()
}
}
ECMA 5
var Shape = function (id, x, y) {
…
};
Shape.prototype.toString = function (x, y) {
return "Shape(" + this.id + ")"
};
var Rectangle = function (id, x, y, width, height) {
Shape.call(this, id, x, y);
…
};
Rectangle.prototype.toString = function () {
return "Rectangle > " + Shape.prototype.toString.call(this);
};
var Circle = function (id, x, y, radius) {
Shape.call(this, id, x, y);
…
};
Circle.prototype.toString = function () {
return "Circle > " + Shape.prototype.toString.call(this);
};
https://stackoverflow.com/questions/4691044
复制相似问题