<html>
<head>
</head>
<body>
<script type="text/javascript">
//工厂模式创建对象,缺点是不能知道对象的类型
function createUser(name,age){
var o = {};
o.name=name;
o.age=age;
o.say=function(){
alert(this.name);
}
return o;
}
//user1 = createUser("tom",11);
//alert(user1.name);
//user2 = createUser("tom1",111);
//user2.say();
//构造函数创建对象。缺点是对象中的方法需要写在构造函数外面,有可能写很多方法
function user(name,age){
this.name=name;
this.age = age;
this.say = say;
}
function say(){
alert(this.name);
}
//var user1 = new user("tom",44);
//var user2 = new user("lily",66);
//alert(user1.name);
//user2.say();
//alert(user1 instanceof user);
//原型模式,缺点是不能有构造函数
function user(){}
user.prototype.name='';
user.prototype.age = 0;
user.prototype.address = [];
user.prototype.say = function(){
alert(this.name);
}
var user1 = new user();
user1.name = 'tom';
user1.age = 11;
user1.address = [1,2];
//user1.address.push("1","2");
var user2 = new user();
user2.name = 'lily';
user2.age = 22;
user2.address = [3,4];
//user2.address.push("3","4");
//alert(user1.name);
//alert(user1.age);
//alert(user1.address);
//user1.say();
//alert(user2.name);
//alert(user2.age);
//alert(user2.address);
//user2.say();
//构造函数+原型模式,构造方法构造属性,原型模式构造方法
function user(name,age){
this.name = name;
this.age = age;
this.address = ['1','2'];
}
user.prototype.say = function(){
alert(this.name);
}
var user1 = new user('tom',11);
var user2 = new user('lily',22);
user1.address.push('a','b');
user2.address = ['cc','dd'];
alert(user1.address);
alert(user2.address);
//动态原型模式
function user(name,age){
this.name = name;
this.age = age;
this.address = ['1','2'];
if(typeof this.say != 'function'){
user.prototype.say = function(){
alert(this.name);
}
}
}
var user1 = new user('tom',11);
var user2 = new user('lily',22);
alert(user1.say==user2.say);
</script>
</body>
<html/>