《JavaScript高級程序設計》筆記:面向對象的程序設計(六)

面向對象的語言有一個標誌,那就是它們都有類的概念,而經過類能夠建立任意多個具備相同屬性和方法的對象。javascript

理解對象

建立自定義對象的最簡單的方法就是建立一個Object的實例,而後再爲它添加屬性和方法。例如:java

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

一樣上面的例子能夠經過對象字面量語法寫成以下:chrome

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

屬性類型

ECMAScript中有兩種屬性:數據屬性和訪問器屬性。數組

1.數據屬性

數據屬性包含一個數據值的位置。在這個位置能夠讀取和寫入值。數據屬性有四個描述其行爲的特性。瀏覽器

Configurable:表示可否通delete刪除屬性從而從新定義屬性,可否修改屬性的特性,或者可否把屬性修改成訪問器屬性。像前面的例子中那樣直接在對象上定義屬性,它們的這個特性默認值爲true。app

Enumerable:表示可否經過for-in循環返回屬性。像前面的例子中那樣直接在對象上定義屬性,它們的這個特性的默認值爲true。函數

Writable:表示可否修改屬性的值。前面例子直接在對象上定義的屬性,它們的這個特性默認值爲true。this

Value:包含這個屬性的數據值。讀取屬性值的時候,從這個位置讀;寫入屬性值的時候,把新值保存到這個位置。這個特性默認值爲undefined。spa

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

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引入的,後來SaFari三、Chrome一、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;
            }
        }
    }
})

讀取屬性的特性

使用Object.getOwnPropertyDescriptor()方法,這個方法接收兩個參數:屬性所在的對象和要讀取的屬性名稱。

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");

從上面的例子能夠看出,要建立一個Person實例,須要使用new操做符。以這種方式調用構造函數要經歷下面四個步驟:

  • 建立一個新對象;
  • 將構造函數的做用域賦給新對象(所以this就指向了這個新對象);
  • 執行構造函數中的代碼(爲這個新對象添加屬性);
  • 返回新對象。

前面生成的兩個person1和person1對象實例,這兩個對象都一constructor屬性,該屬性指向Person,以下代碼:

console.log(person1.constructor == Person); //true
console.log(person2.constructor == Person); //true

對象的constructor屬性最初是用來標識對象類型的。可是,提到檢測對象類型,使用instanceof操做符更可靠些。咱們在上面建立的person1,person2對象既是Object的實例,同時也是Person的實例。

console.log(person1 instanceof Person); //true
console.log(person1 instanceof Object); //true
console.log(person2 instanceof Person); //true
console.log(person2 instanceof Object); //true

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");

但是新問題又來了:在全局做用域中定義的函數實際上只能被某個對象調用,這讓全局做用域有點名存實亡。而更讓人沒法接受的是:若是對象須要定義不少方法,那麼就要定義不少多個全局函數,因而咱們這個自定義的引用類型就絲毫沒有封裝性可言了。好在,這些問題能夠經過使用原型模式來解決。

原型模式

咱們建立的每一個函數都有一個prototype(原型)屬性,這個屬性是一個指針,指向一個對象,而這個對象的用途是包含能夠由特定類型的全部實例共享的屬性和方法。也就是說prototype就是經過調用構造函數而建立的那個實例對象的原型對象。

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);

從圖上能夠看到構造函數Person的屬性prototype指向了函數的原型對象,這個原型對象剛開始只有一個constructor屬性,後面給它添加了原型對象的屬性和方法。person1和person2的實例對象沒有標準的方式訪問[[prototype]],但firefox,safari,chrome在每一個對象上有一個內部屬性__proto__;這個內部屬性__proto__指向了Person.prototype。這兒說明下,Person.prototype.constructor == Person爲true,說明Person.prototype.constructor指回了Person。

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
    

穩妥構造函數模式

所謂穩妥對象,指的是沒有公共屬性,並且其方法也不引用this的對象。

其特色是:一是新建立的對象實例方法不引用this;二是不使用new操做符調用構造函數。

把前面的Person構造函數從新以下:

function Person(name,age,job){
    var o = new Object();
    
   //能夠在這兒建立私有變量和函數
   //方法
    o.sayName = function(){
        console.log(name);
    };
    
    //返回對象
    return o;
}

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

繼承

原型鏈

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

借用構造函數

1.傳遞參數

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

2.借用構造函數的問題

方法都在構造函數中定義,所以函數複用就無從談起。並且在超類型的原型中定義的方法,在子類型中就沒法調用了。

組合繼承

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 createAnother(original){
    var clone = object(original);
    clone.sayHi = function(){
        alert('hi')
    };
    return clone;
}
var person = {
    name:"Nicholas",
    friends:["Shelby", "Court", "Van"]
}

var anotherPerson = createAnother(person);
anotherPerson.sayHi();

寄生組合式繼承

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);
}
相關文章
相關標籤/搜索