言归正传,本文讨论几种js创建对象的方法,先从最好理解的工厂模式开始:
function createPerson(name,age,job){
var o = {};
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
};
return o;
}
var tanya = createPerson("tanya","30","female");
var ansel = createPerson("ansel","30","male");
tanya.sayName();
ansel.sayName();
function createPerson(name,age,job){
var o = {
name : name,
age : age,
job : job,
sayName : function(){
alert(this.name);
}
};
return o;
}
var tanya = createPerson("tanya","30","female");
var ansel = createPerson("ansel","30","male");
tanya.sayName();
ansel.sayName();
function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
}
var tanya = new Person("tanya","30","female");
var ansel = new Person("ansel","30","male");
tanya.sayName();
ansel.sayName();
function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
}
Person("tanya","30","female");
Person("ansel","30","male");
window.sayName();
window.sayName();
function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
}
var olivia = {};
Person.call(olivia,"tanya","30","female");
olivia.sayName();
var philip = {}
Person.apply(philip,["ansel","30","male"]);
philip.sayName();
function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
}
Person.prototype.sayName= function(){
alert(this.name);
};
var tanya = new Person("tanya","30","female");
var ansel = new Person("ansel","30","male");
tanya.sayName();
ansel.sayName();
function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
if (typeof sayName != "function" ){
Person.prototype.sayName= function(){
alert(this.name);
};
}
}
var tanya = new Person("tanya","30","female");
var ansel = new Person("ansel","30","male");
ansel.sayName = function () {
alert("Hi ansel, how hansome you are!");
}
tanya.sayName();
ansel.sayName();
function O(user,pwd){ //use constructor
this.user=user;
this.pwd=pwd;
this.get=get;
return this;
}
function O2(user,pwd){ //use factory
var obj=new Object();
obj.user=user;
obj.pwd=pwd;
obj.get=get;
return obj;
}
function O3(){ //use prototype
}
O3.prototype.user='abc';
O3.prototype.pwd='dis';
// O3.propotype.get='get';
//O3.prototype.get(){
//alert(this.pwd);
//}
function O4(user,pwd){
this.user=user;
this.pwd=pwd;
return this;
}
O4.prototype.get=function(){alert('123');}
//function get(){
//alert("This User:"+this.user);
// }
function test2(){
//var a=new O2('Us','Pw'); use factory & constructor
//var a=new O3(); //use prototype
//a.get();
var a=new O4('*U4','P4'); //混合
//a.user='Not ABC'; //set new property
//alert(a.user);
a.get();
}