- 建立 Prototype 另一種方法可使用 Object Literal Notation 語法
 
function UserInfo(name, age) {
    this.Name = name;
    this.Age = age;
}
UserInfo.prototype.getAge = function() {
    return this.age;
}
var user1 = new UserInfo('Lyndon', 30);
var user2 = new UserInfo('Daisy', 25);
- Object Literal Notation Code
 
function UserInfo(name, age) {
    this.Name = name;
    this.Age = age;
}
UserInfo.prototype = {
    getAge: function() {
        return this.age;
    }
}
var user1 = new UserInfo('Lyndon', 30);
var user2 = new UserInfo('Daisy', 25);
- 結果來看都是一樣,但最大的不同在於 Constructor 屬性會指向 Object 而不是 UserInfo 建構函式,因 Prototype 屬性設定為一個物件時,將會蓋掉原來的 Prototype
 
- 流程圖:找不到 Constructor,因此往上一層找尋 Constructor,所以才指向  Object
 
- 所以須在 Prototype 中,將 Constructor 指回 UserInfo 
 
- Code
 
function UserInfo(name, age) {
    this.Name = name;
    this.Age = age;
}
UserInfo.prototype = {
    constructor: UserInfo,
    getAge: function() {
        return this.age;
    }
}
var user1 = new UserInfo('Lyndon', 30);
var user2 = new UserInfo('Daisy', 25);
- 流程圖:將 Constructor 指回 UserInfo 
 
 
沒有留言:
張貼留言