【发布时间】:2016-01-09 23:16:19
【问题描述】:
我有一个构造函数:
function Point(point, left, right) {
this.p = point;
this.l = left;
this.r = right
}
var bezierPoint = new Point([0.0,0.0],[-50.43794, 0.0],[25.54714,4.78643])
有没有合适的方法来创建一个我可以在所有属性中使用而不是对象本身的方法? 例如如果我想输出
console.log(bezierPoint.l) // -50.43794, 0.0
console.log(bezierPoint.l.round()) // -50, 0
console.log(bezierPoint.r.round()) // 26, 5
或者这是错误的方法,我应该为我将使用的数据类型制定新的方法?类似的东西
Array.prototype.round = function() {
return [Math.round(this[0]), Math.round(this[1])] //this code doesn't matter now
}
console.log(bezierPoint.l.round()) // -50, 0
【问题讨论】:
-
你有不想使用
prototype的原因吗? -
由于
bezierPoint.l似乎返回了一个数组,因此获得所需内容的唯一方法是添加到 Array 构造函数中,而您可能不应该这样做 -
我更喜欢你改变point的原型而不是Array的原型。
-
避免修补 Array 原型。也许希望将这些方法添加到您的 Point 构造函数中。一个例子是
Point.getRounded,它将返回一个四舍五入的top、left和right。bezierPoint.getRounded返回[0,0], [-50, 0], [26, 5]。 -
因此,如果我理解正确,最好为 Point 添加一个方法,这将使用提供的属性来满足我的需要?类似
bezierPoint.getRounded(p)而不是 'bezierPoint.p.getRounded()'
标签: javascript object methods properties