javascript通过prototype添加方法
javascript定义类的构造函数后,其方法可以通过prototype添加
// 定义构造函数
function Point(x, y) {
this.x = x;
this.y = y;
} // 不需要return
let p1 = new Point(2, 2);
let p2 = new Point(1, 2);
Point.prototype.r = function() {
return Math.sqrt(this.x*this.x + this.y*this.y);
}
p1.r(); //=> 2.8284
p2.r(); //=> 2.2360
- 如果如下定义会怎样?
p2.prototype.a = () => { return this.x + this.y;}
Point.prototype.r2 = () => {
return Math.sqrt(this.x*this.x + this.y*this.y);
}