1、JS構造函數
function fn(x, y) {
this.x = x;
this.y = y;
}
使用 var a = new fn(1, 2)
使用prototype進行擴展,在fn.prototype上定義的方法,在所有fn的實例中都能使用,如:
fn.prototype.add = function() {
return this.x + this.y;
}
fn.prototype.constructor === fn
a.__proto__ === fn.prototype
2、Class語法(形式上模仿java、c#,卻失去了它的本性和個性,class是語法糖)
class Fn {
constructor(x, y) {
this.x = x;
this.y = y;
}
add() {
return this.x + this.y;
}
}