【轉載】JavaScript繼承詳解(二)

來源:互聯網
上載者:User

這一章我們將會重點介紹JavaScript中幾個重要的屬性(this、constructor、prototype), 這些屬性對於我們理解如何?JavaScript中的類和繼承起著至關重要的作用。

this

this表示當前對象,如果在全域作用範圍內使用this,則指代當前頁面對象window; 如果在函數中使用this,則this指代什麼是根據運行時此函數在什麼對象上被調用。 我們還可以使用apply和call兩個全域方法來改變函數中this的具體指向。

先看一個在全域作用範圍內使用this的例子:

 

<script type="text/javascript">console.log(this === window);  // trueconsole.log(window.alert === this.alert);  // trueconsole.log(this.parseInt("021", 10));  // 10</script>

 

 

函數中的this是在運行時決定的,而不是函數定義時,如下:

 

// 定義一個全域函數function foo() {console.log(this.fruit);}// 定義一個全域變數,等價於window.fruit = "apple";var fruit = "apple";// 此時函數foo中this指向window對象// 這種調用方式和window.foo();是完全等價的foo();  // "apple"// 自訂一個對象,並將此對象的屬性foo指向全域函數foovar pack = {fruit: "orange",foo: foo};// 此時函數foo中this指向window.pack對象pack.foo(); // "orange"

 

 

全域函數apply和call可以用來改變函數中this的指向,如下:

 

// 定義一個全域函數function foo() {console.log(this.fruit);}// 定義一個全域變數var fruit = "apple";// 自訂一個對象var pack = {fruit: "orange"};// 等價於window.foo();foo.apply(window);  // "apple"// 此時foo中的this === packfoo.apply(pack);    // "orange"

註:apply和call兩個函數的作用相同,唯一的區別是兩個函數的參數定義不同。

 

 

因為在JavaScript中函數也是對象,所以我們可以看到如下有趣的例子:

 

// 定義一個全域函數function foo() {if (this === window) {console.log("this is window.");} }// 函數foo也是對象,所以可以定義foo的屬性boo為一個函數foo.boo = function() {if (this === foo) {console.log("this is foo.");} else if (this === window) {console.log("this is window.");}};// 等價於window.foo();foo();  // this is window.// 可以看到函數中this的指向調用函數的對象foo.boo();  // this is foo.// 使用apply改變函數中this的指向foo.boo.apply(window);  // this is window.

 

 

prototype

我們已經在第一章中使用prototype類比類和繼承的實現。 prototype本質上還是一個JavaScript對象。 並且每個函數都有一個預設的prototype屬性。
如果這個函數被用在建立自訂對象的情境中,我們稱這個函數為建構函式。 比如下面一個簡單的情境:

 

// 建構函式function Person(name) {this.name = name;}// 定義Person的原型,原型中的屬性可以被自訂對象引用Person.prototype = {getName: function() {return this.name;}}var zhang = new Person("ZhangSan");console.log(zhang.getName());   // "ZhangSan"

作為類比,我們考慮下JavaScript中的資料類型 - 字串(String)、數字(Number)、數組(Array)、對象(Object)、日期(Date)等。 我們有理由相信,在JavaScript內部這些類型都是作為建構函式來實現的,比如:

 

 

// 定義數組的建構函式,作為JavaScript的一種預定義類型function Array() {// ...}// 初始化數組的執行個體var arr1 = new Array(1, 56, 34, 12);// 但是,我們更傾向於如下的文法定義:var arr2 = [1, 56, 34, 12];

同時對數組操作的很多方法(比如concat、join、push)應該也是在prototype屬性中定義的。
實際上,JavaScript所有的固有資料類型都具有唯讀prototype屬性(這是可以理解的:因為如果修改了這些類型的prototype屬性,則哪些預定義的方法就消失了), 但是我們可以向其中添加自己的擴充方法。

 

 

// 向JavaScript固有類型Array擴充一個擷取最小值的方法Array.prototype.min = function() {var min = this[0];for (var i = 1; i < this.length; i++) {if (this[i] < min) {min = this[i];}}  return min;};


注意:這裡有一個陷阱,向Array的原型中添加擴充方法後,當使用for-in迴圈數組時,這個擴充方法也會被迴圈出來。
下面的代碼說明這一點(假設已經向Array的原型中擴充了min方法):

 

 

var arr = [1, 56, 34, 12];var total = 0;for (var i in arr) {total += parseInt(arr[i], 10);}console.log(total);   // NaN

解決方案也很簡單:

 

 

var arr = [1, 56, 34, 12];var total = 0;for (var i in arr) {if (arr.hasOwnProperty(i)) {total += parseInt(arr[i], 10);}}console.log(total);   // 103

 

constructor

constructor始終指向建立當前對象的建構函式。比如下面例子:

 

// 等價於 var foo = new Array(1, 56, 34, 12);var arr = [1, 56, 34, 12];console.log(arr.constructor === Array); // true// 等價於 var foo = new Function();var Foo = function() { };console.log(Foo.constructor === Function); // true// 由建構函式執行個體化一個obj對象var obj = new Foo();console.log(obj.constructor === Foo); // true// 將上面兩段代碼合起來,就得到下面的結論console.log(obj.constructor.constructor === Function); // true

 

但是當constructor遇到prototype時,有趣的事情就發生了。
我們知道每個函數都有一個預設的屬性prototype,而這個prototype的constructor預設指向這個函數。如下例所示:

 

function Person(name) {this.name = name;};Person.prototype.getName = function() {return this.name;};var p = new Person("ZhangSan");console.log(p.constructor === Person);  // trueconsole.log(Person.prototype.constructor === Person); // true// 將上兩行代碼合并就得到如下結果console.log(p.constructor.prototype.constructor === Person); // true

當時當我們重新定義函數的prototype時(注意:和上例的區別,這裡不是修改而是覆蓋), constructor的行為就有點奇怪了,如下樣本:

 

 

function Person(name) {this.name = name;};Person.prototype = {getName: function() {return this.name;}};var p = new Person("ZhangSan");console.log(p.constructor === Person);  // falseconsole.log(Person.prototype.constructor === Person); // falseconsole.log(p.constructor.prototype.constructor === Person); // false

為什麼呢?
原來是因為覆蓋Person.prototype時,等價於進行如下代碼操作:

 

 

Person.prototype = new Object({getName: function() {return this.name;}});

而constructor始終指向建立自身的建構函式,所以此時Person.prototype.constructor === Object,即是:

 

 

function Person(name) {this.name = name;};Person.prototype = {getName: function() {return this.name;}};var p = new Person("ZhangSan");console.log(p.constructor === Object);  // trueconsole.log(Person.prototype.constructor === Object); // trueconsole.log(p.constructor.prototype.constructor === Object); // true

怎麼修正這種問題呢?方法也很簡單,重新覆蓋Person.prototype.constructor即可:

 

 

function Person(name) {this.name = name;};Person.prototype = new Object({getName: function() {return this.name;}});Person.prototype.constructor = Person;var p = new Person("ZhangSan");console.log(p.constructor === Person);  // trueconsole.log(Person.prototype.constructor === Person); // trueconsole.log(p.constructor.prototype.constructor === Person); // true

 

下一章我們將會對第一章提到的Person-Employee類和繼承的實現進行完善。

 

轉載自sanshi,原文地址:http://www.cnblogs.com/sanshi/archive/2009/07/08/1519251.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.