一、工廠方式
<script type="text/javascript">
function createObject(name){
var p = new Object();
p.name=name;
p.say = function(){alert(p.name+'ff');}
return p;
}
var p1 = createObject("p1");
var p2 = createObject("p2");
alert(p1.name+" "+p2.name);
p1.say();p2.say();
alert(p1.say==p2.say); //false
</script>
問題:每建立一個對象,對象的方法是新對象,浪費資源
二、構造函數方式
<script type="text/javascript">
function Person(name){
this.name = name;
this.say = function(){
alert("I am "+this.name);
}
}
var p1 = new Person("wang");
var p2 = new Person("li");
p1.say();
p2.say();
alert(p1.say==p2.say); //false
</script>
問題:
建立對象時比工廠方法更易於理解。
和工廠方法同樣,每一個對象都有本身的方法,浪費資源。
三、原型方式
function Person(){}
Person.prototype.name = "";
Person.prototype.say = function(){
alert("I am "+this.name);
}
var p1 = new Person();
var p2 = new Person();
alert(p1.say == p2.say);//true
問題:沒法在構造方法中傳遞參數,全部對象共享屬性。
優勢:對象共方法,節約資源。
四、構造方法+原型方式
function Person(name){
this.name = name;
}
Person.prototype.say = function(){
alert("I am "+this.name);
}
var p1 = new Person("wang");
var p2 = new Person("li");
p1.say();
p2.say();
alert(p1.say==p2.say); //true
優勢:解決了前面提到的問題。
問題:封裝不夠完美。
五、動態原形方式
function Person(name){
this.name = name;
if(Person.prototype.say == undefined){
Person.prototype.say = function(){
alert("I am "+this.name);
}
}
}
var p1 = new Person("wang");
var p2 = new Person("li");
p1.say();
p2.say();
alert(p1.say==p2.say); //true
結論:一種完美的解決方案。
六、對象的建立 - JSON
var person = {};
var girl = {
name:「miss wang」,
age:20,
show = function(){
alert("my name is " + this.name);
}
}
繼承的實現方式
一、 對象冒充
function People(name){
this.name = name;
this.say = function(){
alert("I am "+this.name);
}
}
function WhitePeople(name){
this.inherit = People;
this.inherit(name);
delete this.inherit;
this.color = function(){
alert("I am white people.");
}
}
var p = new WhitePeople("wang");
p.say();
p.color();
alert(p instanceof People); //false
結論:支持多重繼承,但後面的類能夠覆蓋前面類的屬性和方法。繼承後的對象類型和父類對象不匹配
二、利用call()和apply()冒充
function People(name,age){
this.name = name;
this.age = age;
this.say = function(){
alert("I am "+this.name+" "+this.age);
}
}
function WhitePeople(name,age){
//People.call(this,name,age);//call方式以多個參數進行傳值
People.apply(this,[name,age]);//apply方式以數組方式進行傳值
this.color = function(){
alert("I am white people.");
}
}
var p = new WhitePeople("wang",34);
p.say();
p.color();
alert(p instanceof People);
三、原型鏈繼承
//父類
function People(name){
this.name = name;
}
People.prototype.say = function(){
alert("I am "+this.name);
}
//子類
function ChinaPeople(name,area){
People.call(this,name);
this.area = area;
}
ChinaPeople.prototype = new People();
ChinaPeople.prototype.from = function(){
alert("I'am from "+this.area);
}
var p = new ChinaPeople("wang","si chuan");
p.say();
p.from();
alert(p instanceof People); //true
結論:不支持多重繼承,繼承後的對象類型和父類對象匹配javascript