JavaScript精煉之構造函數

學識都 人氣:3.22W

除了創建對象,構造函數(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