構造函數.1
//定義一個 構造函數 以初始化一個新的 Point對象
function Point(x, y) { //照慣例, 構造函數均以大寫字母開始
this.x = x; //關鍵字 this 指代初始化的實例
this.y = y; //將函數參數存儲為對象的屬性
}
//使用 new 關鍵字 和 構造函數 來創建一個實例
var p = new Point(1, 1); //平面幾何中的點(1,1)
//通過給構造函數的 prototype 對象賦值給 Point 對象定義方法
Point.prototype.r = function() {
return Math.sqrt(
this.x * this.x + //返回 x2 + y2 的平方根
this.y * this.y //this 指代 調用這個方法的對象
);
}
//Point的實力對象p (以及所有的Point 實例對象)繼承了方法 r()
console.log(p.r());