一、前言 接著上一篇的內容,繼續JavaScript的學習。 二、內容 屬性類型 創建對象 繼承 ...
一、前言
接著上一篇的內容,繼續JavaScript的學習。
二、內容
屬性類型
//數據屬性
[Configurable] —— 能否通過delete刪除屬性從而重新定義屬性,能否修改屬性的特性,或者修改為訪問器屬性 預設為true
[Enumerable] —— 能否通過for-in迴圈返回屬性 預設為true
[Writeable] —— 能否修改屬性的值 預設為true
[Value] —— 包含這個屬性的數據值 預設為undefined
//要修改屬性預設的特性,必須使用Object.defineProperty()
var person = {};
Object.defineProperty(person,"name",{
writable:false,
value:"Nicholas"
});
alert(person.name); //"Nicholas"
person.name = "Greg" //無效
創建對象
//hasOwnProperty()與in操作符
object.hasOwnProperty("propertyName") //在原型中返回false,在實例中返回true;
"propertyName" in object //無論存在於實例還是原型都返回true
Object.keys(object.prototype); //取得對象上所有可枚舉的實例屬性
Object.getOwnPropertyNames(object.prototype) //取得對象上所有實例屬性,無論是否枚舉
//組合使用構造函數模式與原型模式
創建自定義類型的最常見方式,就是組合使用構造函數模式與原型模式。
定義實例屬性 —— 構造函數模式
定義方法和共用屬性 —— 原型模式
//傳統方式
function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
this.friends = ["Shelby","Court"];
}
Person.prototype = {
constructor:Person,
sayName: function(){
alert(this.name);
}
}
//動態原型方式
function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
this.friends = ["Shelby","Court"];
if(typeof this.sayName != "function"){
Person.prototype.sayName = function(){
alert(this.name);
};
}
}
繼承
//確定原型和實例的關係
alert(instance instanceof Object); //true
alert(Object.prototype.isPrototypeOf(instance)); //true
//偽造對象或經典繼承
function SuperType(){
this.colors = ["red","blue","green"];
}
function SubType(){
SuperType.call(this);
}
//組合繼承 —— 需要兩次調用超類型構造函數
function SuperType(name){
this.name = name;
this.color = ["red","blue","green"];
}
SuperType.prototype.sayName = function(){
alert(this.name);
}
function SubType(name,age){
//繼承屬性
SuperType.call(this,name); //第二次
this.age = age;
}
//繼承方法
SubType.prototype = new SuperType(); //第一次
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function(){
alert(this.age);
}
//原型式繼承
var person = {
name:"Nicholas",
friends:["Shelby","Court","Van"]
};
var anotherPerson = Object.create(person);
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob");
//或
var anotherPerson = Object.create(person,{
name:{
value:"Greg"
}
});
//寄生式繼承
function createAnother(original){
var clone = object(original);
clone.sayHi = function(){
alert("Hi");
};
return clone;
}
var anotherPerson = createAnother(person);
anotherPerson.sayHi();
//寄生組合式繼承 —— 一次調用超類型的構造函數
繼承屬性 —— 借用構造函數
繼承方法 —— 原型鏈的混成形式
function inheritPrototype(subType,superType){
var prototype = object(superType.protoType);
prototype.constructor = subType;
subType.prototype = protype;
}
function SuperType(name){
this.name = name;
this.color = ["red","blue","green"];
}
SuperType.prototype.sayName = function(){
alert(this.name);
}
function SubType(name,age){
//繼承屬性
SuperType.call(this,name);
this.age = age;
}
inheritPrototype(SubType,SuperType);
SubType.prototype.sayAge = function(){
alert(this.age);
}