首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

JScript 自訂物件建立完整指南:建構函式、動態屬性、原型擴充、方法封裝

     編輯:Java 程式設計入門

1. 建構函式定義

function Pasta(grain, width, shape, hasEgg) {
    this.grain = grain;      // 穀物
    this.width = width;      // 寬度
    this.shape = shape;      // 形狀
    this.hasEgg = hasEgg;    // 是否含蛋
}

2. 建立實例

var spaghetti = new Pasta("wheat", 0.2, "circle", true);
var linguine = new Pasta("wheat", 0.3, "oval", true);

3. 動態添加實例屬性

spaghetti.color = "pale straw";
spaghetti.drycook = 7;
// 其他實例不受影響

4. 原型擴充全體實例

Pasta.prototype.foodgroup = "carbohydrates";
// spaghetti.foodgroup、linguine.foodgroup 皆可用

5. 封裝方法於建構函式

function Pasta(grain, width, shape, hasEgg) {
    this.grain = grain;
    this.width = width;
    this.shape = shape;
    this.hasEgg = hasEgg;
    this.toString = pastaToString; // 參考外部函數
}
function pastaToString() {
    return "Grain: " + this.grain + " Width: " + this.width +
           " Shape: " + this.shape + " Egg: " + this.hasEgg;
}
var sp = new Pasta("wheat", 0.2, "circle", true);
window.alert(sp); // 自動呼叫 toString()
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved