筆記 - JS易忘基礎(chǔ)知識(shí)(二)(關(guān)于對(duì)象和繼承)
1 ECMAScript中所有變量都采用晚綁定的方法,不支持早綁定。晚綁定是指我們的代碼在運(yùn)行時(shí)再檢查對(duì)象是否提供了我們所需要的方法和屬性。
2 Array對(duì)象就像一個(gè)棧,提供了push和pop方法。Array對(duì)象又像一個(gè)隊(duì)列,提供了shift和push方法。
3 對(duì)象有為三種:本地對(duì)象、內(nèi)置對(duì)象和宿主對(duì)象。內(nèi)置對(duì)象只有兩個(gè):Global和Math,都屬于本地對(duì)象。
4 ECMAScript只存在公用作用域
5 定義類或?qū)ο笠话闶褂谩皹?gòu)造函數(shù)+原型”方式:用構(gòu)造函數(shù)定義所有非方法的成員,用原型定義方法成員。
實(shí)現(xiàn)繼承一般使用“對(duì)象冒充(object masquerading)+原型鏈”方式:用對(duì)象冒充繼承構(gòu)造函數(shù)的所有成員,用原型鏈繼承原型的方法(用了原型鏈,instanceOf運(yùn)算符才有效)。
function Animal(animalName){this.name = animalName;}
Animal.prototype.showName = function(){alert(this.name);}
function Bird(birdName, birdColor)
{
Animal.call(this, birdName);
this.color = birdColor;
}
Bird.prototype = new Animal();
Bird.prototype.showColor = function(){alert("I am "+ this.color);}
var bird = new Bird("woohu", "red");
bird.showName();
bird.showColor();
6 改進(jìn)字符串處理(將第一段改進(jìn)為第二段,節(jié)約一半時(shí)間):
代碼一:
var str = "hello"; str += "world";
代碼二:
function StringBuffer(){this._strings = new Array();}
StringBuffer.prototype.append = function(str){this._strings.push(str);}
StringBuffer.prototype.toString = function(){retuen this._strings.join("");}
7 極晚綁定:你甚至可以在對(duì)象實(shí)例化后在定義它的方法,如下
var o = new Object();
Object.prototype.fn = function(){alert("hello");};
o.fn();
不過不建議使用極晚綁定,因?yàn)楹茈y對(duì)其進(jìn)行跟蹤和記錄。

浙公網(wǎng)安備 33010602011771號(hào)