對象的創建
使用Object()構造函數或者對面字向量來創建對象
var LY1 = {
name: "LY",
age: 21,
sayname: function() {
alert(this.name);
}
};
LY1.sayname();//使用對象字面量創建對象
var LY2 = new Object();
LY2.name = "LY";
LY2.age = 21;
LY2.sayname = function() {
alert(this.name);
}
LY2.sayname();//使用Object()構造函創建對象
構造函數模式和原型模式
function LY1(name, age) {
this.name = name;
this.age = age;
this.sayname = function() {
alert(this.name);
};
}
var ly1 = new LY1("LY1", 21);
var ly11 = new LY1("LY11", 21); //使用構造函數的方法創建對象
function LY2() {}
LY.prototype.name = "LY2";
LY.prototype.age = 21;
LY.prototype.sayname = function() {
alert(this.name);
}
var ly2 = new LY2();
var ly22 = new LY2(); //使用原型模式構造對象
組合使用構造函數模式和原型模式
function LY(name, age) {
this.name = name;
this.age = age;
}
LY.prototype = {
constructor: LY,
sayName: function() {
alert(this.name);
}
};
var ly1 = new LY();
var ly2= new LY();
這樣創建的兩個對象就既有共享屬性又有自己獨立的屬性動態原型模式
function LY(name, age) {
this.name = name;
this.age = age;
if (typeof this.sayName != "function") {
LY.prototype.sayName = function() {
alert(this.name);
};
}
}
繼承
原型鏈
function Child() {
this.name = "LY";
}
function Parent() {
this.age = 21;
}
Parent.prototype.getAge = function() {
alert(age);
}
Child.prototype = new Parent();
Child.prototype.getName = function() {
alert(this.name);
};
var child = new Child();
將Parent類型的實例賦值給Child類型的原型,賦值之後Child類型的實例child繼承了Parent()的屬性,接着又向Child類型的原型添加了getName()方法借用構造函數
function Parent() {
this.age = 21;
}
function Child() {
Parent.call(this);
}
Child.prototype = new Parent();
var child1 = new Child();
var child2 = new Child();
這樣在創建child1和child2是就會分別創建Parent()的實例,在修改child1時就不會對child2產生影響組合繼承
function Parent() {
this.age = 21;
}
function Child() {
this.name = "LY";
Parent.call(this);
}
Child.prototype = new Parent();
var child1 = new Child();
var child2 = new Child();
在上面的代碼中,借用call()函數使得Child()函數獲得Parent()函數中的屬性。使用原型鏈獲得Parent原型中的方法組合繼承是JavaScript中使用較多的繼承方式