標籤:index string width enum 特性 color 繼承 alert 面向
EcmaScript有兩種屬性 |
資料屬性 和 訪問器屬性 |
資料屬性有4個特性 |
ConfigurableEnumerableWritableValue 前三個值的預設值都為false 舉例Object.defineProperty( person, "name", { writable:false, value:"niko"} ) ; 一旦屬性定義為不可配置的,就不能再把它變回可配置的了 |
讀取屬性 的特性 |
var descriptor = Object.getOwnPropertyDescriptor( book, "_year" )descriptor.valuedescriptor.configurable |
使用建構函式模式建立對象 |
function Person( name,age,job ){ this.name = name ; this.age = age ; this.sayName = function(){ alert( this.name ) }} |
用原型模式建立對象 |
function Person(){}Person.prototype.name = "jeff";Person.prototype.age = 28好處是 可以讓所有對象執行個體共用它所包含的屬性和方法,Person.prototype指向了原型對象 而Person.prototpe.constuctor 又指向了Person |
判斷類型 |
Person.prototype.isPrototypeOf( person1 ) // true Object.getPrototypeOf( person1 ) == Person.prototype ) ; //true |
判斷一個屬性是在原型中,而不是在執行個體中 |
function hasPrototypeProperty( object, name ){ return !object.hasOwnProperty( name ) && ( name is object ) ; |
取得對象上所有可枚舉的執行個體屬性 |
Object.keys() 方法 |
如果你想要得到所有執行個體屬性,無論它是否可枚舉,都可以用方法 |
Object.getOwnPropertyNames() dvar keys = Object.getOwnPropertyNames( Person.prototype );//"constructor name age job sayName |
使用constructor不能確定對象的類型 |
var friend = new Person()friend instanceof Object //truefriend instanceof Person //truefriend.constructor == Person // falsefriend.constructor == Object // true |
執行個體 和 原型 之間通過什麼連結 |
只是一個指標 而非副本 |
在原生對象的原型上添加方法 |
String.prototype.startWith = function(text) { return this.indexOf(text) == 0 }var msg = "hello world"msg.startWith("hello"); |
原型對象的缺點 |
最大問題是 由其共用的本性所導致的function Person(){}Person.prototype = { constructor:Person, name:"nico",friends:["a","b"]}var p0 = new Person();var p1 = new Person();p0.friends.push("c");那麼p1的friends裡也會有c |
組合使用建構函式模式 和 原型模式 |
建構函式模式用於定義 執行個體屬性 ,而原型模式用於定義方法和共用的屬性function Person( name, age, job ){ this.name = name; this.age = age ; this.job = job ;}Person protytype = { constructor:Person, sayName: function(){ alert( this.name ) ; }} |
動態原型模式 |
function Person( name, age, job ){ this.name = name this.age = age ; this.job = job ; if( typeof this.sayName != "function" ){ Person.prototype.sayName = function(){} ; }} |
寄生建構函式模式 |
待補 |
穩妥建構函式模式 |
待補 |
繼承 |
待補 |
讀書筆記 - js進階程式設計 - 第六章 物件導向的程式設計