1. 程式人生 > >《JavaScript高階程式設計》筆記:面向物件的程式設計(六)

《JavaScript高階程式設計》筆記:面向物件的程式設計(六)

面向物件的語言有一個標誌,那就是它們都有類的概念,而通過類可以建立任意多個具有相同屬性和方法的物件。

理解物件

建立自定義物件的最簡單的方法就是建立一個Object的例項,然後再為它新增屬性和方法。例如:

var person = new Object();
    person.name="Nicholas";
    person.age=29;
    person.job="Software Engineer";
    person.SayName=function(){
        alert(this.name);
    }

同樣上面的例子可以通過物件字面量語法寫成如下:

var person ={
        name:"Nicholas",
        age:29,
        person.job:"Software Engineer",
        SayName:function(){
            alert(this.name);
        }
    }

屬性型別

ECMAScript中有兩種屬性:資料屬性和訪問器屬性。

1.資料屬性

資料屬性包含一個數據值的位置。在這個位置可以讀取和寫入值。資料屬性有四個描述其行為的特性。

Configurable:表示能否通delete刪除屬性從而重新定義屬性,能否修改屬性的特性,或者能否把屬性修改為訪問器屬性。像前面的例子中那樣直接在物件上定義屬性,它們的這個特性預設值為true。

Enumerable:表示能否通過for-in迴圈返回屬性。像前面的例子中那樣直接在物件上定義屬性,它們的這個特性的預設值為true。

Writable:表示能否修改屬性的值。前面例子直接在物件上定義的屬性,它們的這個特性預設值為true。

Value:包含這個屬性的資料值。讀取屬性值的時候,從這個位置讀;寫入屬性值的時候,把新值儲存到這個位置。這個特性預設值為undefined。

對於前面的例子,value特性被設定為特定的值。例如:

var person={
    name="Niceholas"
}

這裡建立一個名為name的屬性,為它指定的值是"Niceholas"。也就是說value特性將被設定為"Niceholas",而對這個值的任何修改都將反映在這個位置。

要修改屬性預設的特性,必須使用ECMAScript5的Object.defineProperty()方法。這個方法接收三個引數:屬性所在的物件、屬性名字和一個描述符物件。其中,描述符物件的屬性必須是Configurable、Enumerable、Writable、Value。設定其中的一或多個值。可以修改對應的特性值。例如:

var person={};
    Object.defineProperty(person,"name",{
        writable:false,
        value:'Nich'
    });
    
    alert(person.name);//Nich
    person.name="Greg";
    alert(person.name);//Nich

這個例子建立了一個名為name的屬性,它的值為Nich是隻讀的。這個屬性的值是不可以修改的,如果嘗試為它指定新值,則在非嚴格模式下,賦值操作將被忽略;在嚴格模式下,賦值操作將會丟擲錯誤。
類似的規則也適用與不可配置的屬性。例如:

var person={};
    Object.defineProperty(person,"name",{
        configurable:false,
        value:'Nich'
    });
    
    alert(person.name);//Nich
    delete person.name;
    alert(person.name);//Nich
    
    

注意:一旦把屬性定義為不可配置的,就不能再把它變回可配置了。此時,再呼叫Object.defineProperty()方法修改除了writable之外的特性,都會導致錯誤。

var person={};
    Object.defineProperty(person,"name",{
        configurable:false,
        value:'Nich'
    });

    //丟擲錯誤
    Object.defineProperty(person,"name",{
        configurable:true,
        value:'Nich'
    });
    

也就是說,多次呼叫Object.defineProperty()方法修改同一個屬性,但是把configurable特性設定為false之後就會有限制了。
在呼叫Object.defineProperty()方法時,如果不指定,configurable、Enumerable和writable特性的預設值為false。多數情況下,可能都沒有必要利用Object.defineProperty()方法提供的這些高階功能。不過,理解這些概念對於理解javascript物件卻非常有用。

注:IE8是第一個實現Object.defineProperty()方法的瀏覽器版本。然而,這個版本的實現存在諸多的限制:只能在DOM物件上使用這個方法,而且只能建立訪問器屬性。由於實現不徹底,建議不要在IE8中使用Object.defineProperty()方法。

2.訪問器屬性
訪問器屬性不包含資料值;它們包含一對兒getter和setter函式(不過,這兩個函式都不是必需的)。

在讀取訪問器屬性時,會呼叫getter函式,這個函式負責返回有效的值;在寫入訪問器屬性時,會呼叫setter函式並傳入新值,這個函式負責決定如何處理資料。訪問器屬性有如下4個特性。

  • [Configurable]:表示能否通過delete刪除屬性從而重新定義屬性,能否修改屬性的特性,或者能否把屬性修改為資料屬性。對於直接在物件上定義的屬性,這個特性的預設值為true。
  • [Enumerable]:表示能否通過for-in迴圈返回屬性。對於直接在物件上定義的屬性,這個特性預設值為true。
  • [Get]:在讀取屬性時呼叫的函式。預設值為undefined。
  • [Set]:在寫入屬性時呼叫的函式。預設值為undefined。

訪問器屬性不能直接定義,必須使用Object.defineProperty()來定義。下面例子:

var book={
        _year:2004,
        edition:1
    }
    Object.defineProperty(book,"year",{
        get:function(){
            return this._year;
        },
        set:function(newValue){
            console.log(newValue);
            if(newValue>2004){
                this._year=newValue;
                this.edition+=newValue-2004;
            }
        }
    });
    book.year=2005;
    console.log(book.edition);//2

//上面程式碼建立了一個book物件,並給它定義兩個預設的屬性:_year和edition。_year前面的下劃線是一種常用的記號,用於表示只能通過物件方法訪問的屬性。


//支援ECMAScript5的這個方法的瀏覽器有IE9+、Firefox4+、SaFari5+、Opera12+和Chrome。在這個方法之前,要建立訪問器屬性,一般都使用兩個非標準的方法:__defineGetter__()和__defineSetter__()。這2個方法最初是由Firefox引入的,後來SaFari3、Chrome1、opera9.5也給出了相同的實現。使用這2個遺留的方法,可以實現上面的例子如下:
var book={
    _year:2004,
    edition:1
}
//定義訪問器的舊有方法
book.__defineGetter__('year',function(){
    return this._year;
});
book.__defineSetter__('year',function(newValue){
    if(newValue>2004){
        this._year=newValue;
        this.edition+=newValue-2004;
    }
});
book.year=2005;
alert(book.edition);//2

在不支援Object.defineProperty()方法的瀏覽器中不能修改[Configurable] 和[Enumerable]。

定義多個屬性

ECMAScript5又定義了一個Object.defineProperties()方法。這個方法接收兩個物件引數:第一個物件是要新增和修改其屬性的物件;第二個物件的屬性與第一個物件中新增或修改的屬性一一對應。例如:

var book={}

Object.defineProperties(book,{

    _year:{
        value:2004
    },
    edition:{
        value:1
    },
    year:{

        get:function(){
            return this._year;
        },
        set:function(newValue){
            if(newValue>2004){
                this._year=newValue;
                this.edition+=newValue-2004;
            }
        }
    }
})

讀取屬性的特性

var book={};
Object.defineProperties(book,{

    _year:{
        value:2004
    },
    edition:{
        value:1
    },
    year:{

        get:function(){
            return this._year;
        },
        set:function(newValue){
            if(newValue>2004){
                this._year=newValue;
                this.edition+=newValue-2004;
            }
        }
    }
})

var descriptor=Object.getOwnPropertyDescriptor(book,'_year');
alert(descriptor.value);//2004
alert(descriptor.configurable);//false
alert(typeof descriptor.get);//undefined

var descriptor=Object.getOwnPropertyDescriptor(book,'year');
alert(descriptor.value);//undefined
alert(descriptor.configurable);//false
alert(typeof descriptor.get);//'function'

建立物件

雖然object建構函式或物件字面量都可以用來建立單個物件。但這些方式有個明顯的缺點:使用同一個介面建立很多物件,會產生大量重複程式碼。

工廠模式

function createPerson(name, age,job){
    var o = new Object();
    o.name = name;
    o.age = age;
    o.job = job;
    o.sayName = function(){
        alert(this.name);
    }

    return o;
}

var person1 = createPerson("Nicholas", 29, "Software Engineer");
var person2 = createPerson("Greg", 27, "Doctor");

工廠模式雖然解決了建立多個相似物件的問題,但卻沒有解決物件識別的問題(即怎樣知道一個物件的型別)。

建構函式模式

function Person(name, age,job){
    this.name = name;
    this.age = age;
    this.job = job;
    this.sayName = function(){
        alert(this.name);
    }
   
}

var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");

1.將建構函式當函式
例如前面例子中的Person函式可以用下面任何一種方式呼叫:

//當成建構函式使用
var person1 = new Person("Nicholas", 29, "Software Engineer");
person1.sayName();//Nicholas
//作為普通函式呼叫
Person("Greg", 27, "Doctor");
window.sayName();//Greg 


//在另一個物件的作用域中呼叫
var o=new Object();
Person.call(o,"Kristen",25,"Nurse");
o.sayName();
    

2.建構函式的問題

function Person(name,age,job){
    this.name = name;
    this.age = age;
    this.job = job;
    this.sayName = new Function("console.log(this.name)"); // 與宣告函式在邏輯上是等價的
}

以這種方法建立函式,會導致不同的作用域鏈和標示符解析。不同例項上的同名函式是不相等的。

var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
console.log(person1.sayName == person2.sayName); // false  

然後,建立兩個完成同樣任務的Function例項的確沒有必要;況且有this物件在,根本不用在執行程式碼前就把函式繫結到特定物件上面。因此,大可像下面這樣,通過把函式定義轉移到建構函式外部來解決這個問題。

function Person(name, age,job){
    this.name = name;
    this.age = age;
    this.job = job;
    this.sayName = sayName;
}

function sayName(){
    alert(this.name);
}

var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");

可是新問題又來了:在全域性作用域中定義的函式實際上只能被某個物件呼叫,這讓全域性作用域有點名不副實。而更讓人無法接受的是:如果物件需要定義很多方法,那麼就要定義很多多個全域性函式,於是我們這個自定義的引用型別就絲毫沒有封裝性可言了。好在,這些問題可以通過使用原型模式來解決。

原型模式

function Person(){}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software  Engineer";
Person.prototype.sayName = function(){
    alert(this.name);
}

var person1 = new Person();
person1.sayName(); // Nicholas

var person2 = new Person();
person2.sayName(); // Nicholas
alert(person1.sayName == person2.sayName);

isPrototypeOf()

console.log(Person.prototype.isPrototypeOf(person1)); // true
console.log(Person.prototype.isPrototypeOf(person2)); // true

hasOwnProperty()

function Person(){}

Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software  Engineer";
Person.prototype.sayName = function(){
    console.log(this.name);
}

var person1 = new Person();
var person2 = new Person();

console.log(person1.hasOwnProperty("name")); // false

person1.name = "Greg";
console.log(person1.name); // Greg
console.log(person1.hasOwnProperty("name")); // true

console.log(person2.name); // Nicholas
console.log(person2.hasOwnProperty("name")); // false

delete person1.name;
console.log(person1.name); // Nicholas
console.log(person1.hasOwnProperty("name")); // false

原型與in操作符

function Person(){}

Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software  Engineer";
Person.prototype.sayName = function(){
    console.log(this.name);
}

var person1 = new Person();
var person2 = new Person();

console.log(person1.hasOwnProperty("name")); // false
console.log("name" in person1); // true

person1.name = "Greg";
console.log(person1.name); // Greg
console.log(person1.hasOwnProperty('name')); // true
console.log("name" in person1); // true


console.log(person2.name); // Nicholas
console.log(person2.hasOwnProperty('name')); // false
console.log("name" in person2); // true

delete person1.name;
console.log(person1.name); // Nicholas
console.log(person1.hasOwnProperty('name')); // false
console.log("name" in person1); // true

同時使用hasOwnProperty()方法和in操作符,就可以確定該屬性到底是存在於物件中,還是存在於原型中,如下:

function hasPrototypeProperty(object,name){
    return !object.hasOwnProperty(name)&&(name in object);
}

只要in操作符返回true而hasOwnProperty()返回false,就可以確定屬性是原型中的屬性。

更簡單的原型語法

function Person(){}

Person.prototype = {
    name: "Nicholas", 
    age:29,
    job: "Software Engineer",
    sayName: function(){
        console.log(this.name);
    }
}

var friend = new Person();
console.log(friend instanceof Object); // true
console.log(friend instanceof Person); // true
console.log(friend.constructor == Person); // false
console.log(friend.constructor == Object); // true

如果constructor的值真的很重要,可以像下面這樣特意將它設定回適當的值。

function Person(){}

Person.prototype = {
    constructor: Person,
    name: "Nicholas", 
    age:29,
    job: "Software Engineer",
    sayName: function(){
        console.log(this.name);
    }
}

原型物件的問題

function Person(){}

Person.prototype = {
    constructor: Person,
    name: "Nicholas", 
    age:29,
    job: "Software Engineer",
    friends: ['Shelby', "Court"],
    sayName: function(){
        console.log(this.name);
    }
}

var person1 = new Person();
var person2 = new Person();

person1.friends.push("Van");

console.log(person1.friends); //Shelby,Court,Van
console.log(person2.friends); //Shelby,Court,Van
console.log(person1.friends===person2.friends); // true

假如我們的初衷就是像這樣在所有例項中共享一個數組,那麼對這個結果無話可說。可是,例項一般都是要有屬於自己的全部屬性的。而這個問題正是我們很少看到有人單獨使用原型模式的原因所在。

組合使用建構函式模式和原型模式

function Person(name,age,job){
    this.name = name;
    this.age = age;
    this.job = job;
    this.friends = ["Shelby", "Court"];
}

Person.prototype = {
    constructor: Person,
    sayName: function(){ console.log(this.name);}
}

var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");

person1.friends.push("Van");
console.log(person1.friends); // Shelby, Count, Van
console.log(person2.friends); // Shelby, Count
console.log(person1.friends === person2.friends); // false
console.log(person1.sayName === person2.sayName); // true

在這個例子中,例項屬性都是在建構函式中定義的,而由所有例項共享的屬性constructor和方法sayName()則是在原型中定義的。這種建構函式與原型混成的模式,是目前認同度最高的一種建立自定義型別的方法。

動態原型模式

function Person(name, age,job){
    this.name = name;
    this.age = age;
    this.job = job;
}

if (typeof this.sayName!='function'){
    Person.prototype.sayName = function(){
        console.log(this.name);
   }
}

var friend = new Person("Nicholas",29,"Software Engineer");
friend.sayName(); //Nicholas

寄生建構函式模式

function Person(name,age,job){
    var o = new Object();
    o.name = name;
    o.age = age;
    o.job = job;
    o.sayName = function(){
        console.log(this.name);
    };
    return o;
}

var friend = new Person("Nicholas", 29, "Software Engineer");
friend.sayName(); // Nicholas

關於寄生建構函式模式,返回的物件與建構函式或者建構函式的原型屬性之間沒有關係;也就是說,建構函式返回的物件與在建構函式外部建立的物件沒有什麼不同。

 function SpecialArray(){
        var values=new Array();
        values.push.apply(values,arguments);
        values.toPipedString=function(){
            return this.join("|");
        }
        return values;
    }
    var colors=new SpecialArray("red","blue","green");
    console.log(colors.toPipedString()); //red|blue|green
    

繼承

原型鏈

function SuperType(){
     this.property= true;
}

SuperType.prototype.getSuperValue = function(){
    return this.property;
};

function Subtype(){
    this.subproperty = false;
}

// 繼承了SuperType
Subtype.prototype = new SuperType();

Subtype.prototype.getSubValue = function(){
    return this.subproperty;
}

var instance = new Subtype();
console.log(instance.getSuperValue()); // true

謹慎地定義方法

function SuperType(){
     this.property= true;
}

SuperType.prototype.getSuperValue = function(){
    return this.property;
};

function Subtype(){
    this.subproperty = false;
}

// 繼承了SuperType
Subtype.prototype = new SuperType();

Subtype.prototype = {
    getSubValue: function(){
        return this.subproperty;
    },
    someOtherMethod: function(){
        return false;
    }
};

var instance = new Subtype();
console.log(instance.getSuperValue()); // error

原型鏈的問題

包含引用型別值的原型屬性會被所有例項共享;而這也正是為什麼要在建構函式中,而不是在原型物件中定義屬性的原因。
在建立子型別的例項時,不能向超型別的建構函式中傳遞引數。實際上,應該說是沒有辦法在不影響所有物件例項的情況下,給超型別的建構函式傳遞引數。

function SuperType(){
    this.colors = ["red", "blue", "green"];
}

function Subtype(){
    
}
Subtype.prototype= new SuperType();
var instance1 = new Subtype();
instance1.colors.push("black");
console.log(instance1.colors); // red, blue, green, black

var instance2 = new Subtype();
console.log(instance2.colors); // red, blue, green, black

傳遞引數

function SuperType(name){
    this.name = name;
}

function Subtype(){
    SuperType.call(this,"Nicholas");
    this.age = 29;
}

var instance = new Subtype();
console.log(instance.name); //Nicholas
console.log(instance.age); // 29

組合繼承

function SuperType(name){
    this.name = name;
    this.colors = ["red", "blue", "green"];
}

SuperType.prototype.sayName = function(){
    console.log(this.name);
};

function Subtype(name,age){
    SuperType.call(this,name);
    this.age = age;
}

Subtype.prototype = new SuperType();
Subtype.prototype.sayAge = function(){
   console.log(this.age);
};

var instance1 = new Subtype("Nicholas", 29);
instance1.colors.push("black");
console.log(instance1.colors); // red, blue, green, black
instance1.sayName(); // Nicholas
instance1.sayAge(); //29

var instance2 = new Subtype("Greg", 2);
console.log(instance2.colors); // red, blue, green
instance2.sayName(); // Greg
instance2.sayAge(); //2

組合繼承避免了原型鏈和借用函式的缺陷,融合了它們的優點,成為Javascript中最常用的繼承模式。

原型式繼承

function object(o){
    function F(){}
    F.prototype = o;
    return new F();
}
var person = {
    name:"Nicholas",
    friends:["Shelby", "Court", "Van"]
};

var anotherPerson = object(person);
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob");

var yetAnotherPerson = object(person);
yetAnotherPerson.name = "Linda";
yetAnotherPerson.friends.push("Barbie");

console.log(person.friends); // Shelby, Court, Van, Rob, Barbie

Object.create()

Object.create()方法規範了原型式繼承。

var person = {
    name:"Nicholas",
    friends:["Shelby", "Court", "Van"]
};

var anotherPerson = Object.create(person);
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob");

var yetAnotherPerson = Object.create(person);
yetAnotherPerson.name = "Linda";
yetAnotherPerson.friends.push("Barbie");

console.log(person.friends); // Shelby, Court, Van, Rob, Barbie

寄生式繼承

function object(o){
    function F(){}
    F.prototype = o;
    return new F();
}

function inheritPrototype(subType,superType){
    var prototype = object(superType.prototype);
    prototype.constructor = subType;
    subType.prototype = prototype;
}

function SuperType(name){
    this.name = name;
    this.colors = ["red", "blue", "green"];
}

SuperType.prototype.sayName = function(){
    console.log(this.name);
}

function Subtype(name,age){
    SuperType.call(this,name);
    this.age = age;
}

inheritPrototype(Subtype, SuperType);

Subtype.prototype.sayAge = function(){
    console.log(this.age);
}