對象和繼承(Objects and inheritance)

2018-06-15 18:54 更新

和所有的值類型一樣,對象有屬性。事實上,你可以將對象當(dāng)作一組屬性的集合,每個屬性都是一對(鍵和值)。鍵是字符串,值可以是任意JavaScript值。到目前為止,我們僅僅見過鍵是標(biāo)識符的屬性,因為點操作符處理的鍵必須為標(biāo)識符。在這節(jié),你講見到另一種訪問屬性的方法,能將任意字符串作為鍵。

單個對象(Single objects)

在JavaScript中,你可以直接創(chuàng)建對象,通過對象字面量:

var jane = {
    name: 'Jane',


    describe: function () {
        'use strict';
        return 'Person named '+this.name;
    }
};

上面的對象有兩個屬性:namedescribe。你能讀(“get”)和 寫(“set”)屬性:

> jane.name  // get
'Jane'
> jane.name = 'John';  // set
> jane.newProperty = 'abc';  // 自動創(chuàng)建

屬性是函數(shù)如 describe 可以被當(dāng)作方法調(diào)用。當(dāng)調(diào)用他們時可以在它們內(nèi)部通過this引用對象。

> jane.describe()  // 調(diào)用方法
'Person named John'
> jane.name = 'Jane';
> jane.describe()
'Person named Jane'

in 操作符用來檢測一個屬性是否存在:

> 'newProperty' in jane
true
> 'foo' in jane
false

若讀取一個不存在的屬性,將會得到undefined值。因此上面的兩個檢查也可以像下面這樣:

> jane.newProperty !== undefined
true
> jane.foo !== undefined
false

delete操作符用來刪除一個屬性:

> delete jane.newProperty
true
> 'newProperty' in jane
false

任意鍵屬性(Arbitrary property keys)

屬性的鍵可以是任意字符串。到目前為止,我們看到的對象字面量中的和點操作符后的屬性關(guān)鍵字。按這種方法你只能使用標(biāo)識符。如果你想用其他任意字符串作為鍵名,你必須在對象字面量里加上引號,并使用方括號獲取和設(shè)置屬性。

> var obj = { 'not an identifier': 123 };
> obj['not an identifier']
123
> obj['not an identifier'] = 456;

方括號允許你動態(tài)計算屬性關(guān)鍵字:

> var x = 'name';
> jane[x]
'Jane'
> jane['na'+'me']
'Jane'

引用方法(Extracting methods)

如果你引用一個方法,它將失去和對象的連接。就其本身而言,函數(shù)不是方法,其中的this值為undefined(嚴(yán)格模式下)。

> var func = jane.describe;
> func()
TypeError: Cannot read property 'name' of undefined

解決辦法是使用函數(shù)內(nèi)置的bind()方法。它創(chuàng)建一個新函數(shù),其this值固定為給定的值。

> var func2 = jane.describe.bind(jane);
> func2()
'Person named Jane'

方法內(nèi)部的函數(shù)(Functions inside a method)

每個函數(shù)都有一個特殊變量this。如果你在方法內(nèi)部嵌入函數(shù)是很不方便的,因為你不能從函數(shù)中訪問方法的this。下面是一個例子,我們調(diào)用forEach循環(huán)一個數(shù)組:

var jane = {
    name: 'Jane',
    friends: [ 'Tarzan', 'Cheeta' ],
    logHiToFriends: function () {
        'use strict';
        this.friends.forEach(function (friend) {
            // 這里的“this”是undefined
            console.log(this.name+' says hi to '+friend);
        });
    }
}

調(diào)用 logHiToFriends 會產(chǎn)生錯誤:

> jane.logHiToFriends()
TypeError: Cannot read property 'name' of undefined

有兩種方法修復(fù)這問題。

1:將this存儲在不同的變量。

logHiToFriends: function () {
    'use strict';
    var that = this;
    this.friends.forEach(function (friend) {
        console.log(that.name+' says hi to '+friend);
    });
}

2:forEach的第二個參數(shù)允許提供this值。

logHiToFriends: function () {
    'use strict';
    this.friends.forEach(function (friend) {
        console.log(this.name+' says hi to '+friend);
    }, this);
}

在JavaScript中函數(shù)表達(dá)式經(jīng)常被用作函數(shù)參數(shù)。時刻小心函數(shù)表達(dá)式中的this。

構(gòu)造函數(shù):對象工廠(Constructors: factories for objects)

目前為止,你可能認(rèn)為JavaScript的對象僅是鍵值的映射,通過JavaScript對象字面量可以得出這個觀點,看起來很像其他語言中的地圖/字典(map/dictionary)。然而,JavaScript對象也支持真正意義上的面向?qū)ο筇匦裕豪^承(inheritance)。本節(jié)不會完全講解JavaScript中繼承的工作原理,但會給你以此為開始的簡單模式。如果你想得到更多知識,請查閱這篇文章“JavaScript inheritance by example”。 除了作為“真正”的函數(shù)和方法,函數(shù)還在JavaScript中扮演第三種角色:如果通過new操作符調(diào)用,他們會變?yōu)闃?gòu)造函數(shù),對象的工廠。構(gòu)造函數(shù)是對其他語言中的類的粗略模擬。約定俗成,構(gòu)造函數(shù)的第一個字母大寫。例如:

// 設(shè)置實例數(shù)據(jù)
function Point(x, y) {
    this.x = x;
    this.y = y;
}
// 方法
Point.prototype.dist = function () {
    return Math.sqrt(this.x*this.x + this.y*this.y);
};

我們看到構(gòu)造函數(shù)分為兩部分:首先,Point函數(shù)設(shè)置實例數(shù)據(jù)。其次,Point.prototype屬性包含對象的方法。前者的數(shù)據(jù)是每個實例私有的,后面的數(shù)據(jù)是所有實例共享的。 我們通過new操作符調(diào)用Point:

> var p = new Point(3, 5);
> p.x
3
> p.dist()
5.830951894845301

p是Point的一個實例:

> p instanceof Point
true
> typeof p
'object'

深入閱讀

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號