當前位置:才華齋>設計>網頁設計>

JavaScript精煉之建構函式

網頁設計 閱讀(1.46W)

除了建立物件,建構函式(constructor) 還做了另一件有用的事情—自動為建立的新物件設定了原型物件(prototype object) 。原型物件存放於 otype 屬性中。

JavaScript精煉之建構函式

例如,我們重寫之前例子,使用建構函式建立物件“b”和“c”,那麼物件”a”則扮演了“otype”這個角色:

// 建構函式function Foo(y) { // 建構函式將會以特定模式建立物件:被建立的物件都會有"y"屬性 this.y = y;}// "otype"存放了新建物件的原型引用// 所以我們可以將之用於定義繼承和共享屬性或方法// 所以,和上例一樣,我們有了如下程式碼:// 繼承屬性"x"otype.x = ;// 繼承方法"calculate"ulate = function (z) { return this.x + this.y + z;};// 使用foo模式建立 "b" and "c"var b = new Foo();var c = new Foo();// 呼叫繼承的方法ulate(); // ulate(); // // 讓我們看看是否使用了預期的屬性( b.__proto__ === otype, // true c.__proto__ === otype, // true // "otype"自動建立了一個特殊的屬性"constructor" // 指向a的建構函式本身 // 例項"b"和"c"可以通過授權找到它並用以檢測自己的建構函式 tructor === Foo, // true tructor === Foo, // true tructor === Foo // true ulate === b.__proto__ulate, // true b.__proto__ulate === ulate // true);

上述程式碼可表示為如下的.關係:

建構函式與物件之間的關係

上述圖示可以看出,每一個object都有一個prototype. 建構函式Foo也擁有自己的__proto__, 也就是otype, 而otype的__proto__指向了otype. 重申一遍,otype只是一個顯式的屬性,也就是b和c的__proto__屬性。

這個問題完整和詳細的解釋有兩個部分:

面向物件程式設計.一般理論(OOP. The general theory),描述了不同的面向物件的正規化與風格(OOP paradigms and stylistics),以及與ECMAScript的比較。

面向物件程式設計Script實現(OOP. ECMAScript implementation), 專門講述了ECMAScript中的面向物件程式設計。

現在,我們已經瞭解了基本的object原理,那麼我們接下去來看看ECMAScript裡面的程式執行環境[runtime program execution]. 這就是通常稱為的“執行上下文堆疊”[execution context stack]。每一個元素都可以抽象的理解為object。你也許發現了,沒錯,在ECMAScript中,幾乎處處都能看到object的身影。

下面給大家介紹JavaScript constructor 屬性詳解

物件的constructor屬性用於返回建立該物件的函式,也就是我們常說的建構函式。

在JavaScript中,每個具有原型的物件都會自動獲得constructor屬性。除了arguments、Enumerator、Error、Global、Math、RegExp、Regular Expression等一些特殊物件之外,其他所有的JavaScript內建物件都具備constructor屬性。例如:Array、Boolean、Date、Function、Number、Object、String等。所有主流瀏覽器均支援該屬性。

語法

tructor

返回值

物件的constructor屬性返回建立該物件的函式的引用。

示例&說明

以下程式碼中的[native code],表示這是JavaScript的底層內部程式碼實現,無法顯示程式碼細節。

// 字串:String()var str = "張三";eln(tructor); // function String() { [native code] }eln(tructor === String); // true// 陣列:Array()var arr = [1, 2, 3];eln(tructor); // function Array() { [native code] }eln(tructor === Array); // true// 數字:Number()var num = 5;eln(tructor); // function Number() { [native code] }eln(tructor === Number); // true// 自定義物件:Person()function Person(){ = "CodePlayer";}var p = new Person();eln(tructor); // function Person(){ = "CodePlayer"; }eln(tructor === Person); // true// JSON物件:Object()var o = { "name" : "張三"};eln(tructor); // function Object() { [native code] }eln(tructor === Object); // true// 自定義函式:Function()function foo(){ alert("CodePlayer");}eln(tructor); // function Function() { [native code] }eln(tructor === Function); // true// 函式的原型:bar()function bar(){ alert("CodePlayer");}eln(tructor); // function bar(){ alert("CodePlayer"); }eln(tructor === bar); // true