<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>javascript 创建对象</title>
<script type="text/javascript" src="js/common.js"></script>
<script type="text/javascript">
println("---对象创建方式---");
//构造函数模式
println("----构造函数模式-----");
function Person(name,color){
this.name = name;
this.color = color;
this.sayName = function(){
println("name = " + this.name);
}
}
var p = new Person("zizhu", "red");
p.sayName();
//原型模式
println("----原型模式-----");
function Dog(){}
Dog.prototype.name = "zizhu8";
Dog.prototype.color = "black";
Dog.prototype.showInfo = function(){
println("name = " + this.name + ", color = " + this.color);
}
var dog = new Dog();
dog.showInfo();
//组合模式
println("----组合模式-----");
function Pig(name,color){
this.name = name;
this.color = color;
}
Pig.prototype.showInfo = function(){
println("name = " + this.name + ", color = " + this.color);
}
var pig = new Pig("pig", "blue");
pig.showInfo();
//动态模式
println("---动态模式---");
function Cow(name,color){
this.name = name;
this.color = color;
if(typeof this.showInfo != "function"){
alert("first alert!!!");
Cow.prototype.showInfo = function(){
println("name = " + this.name + ", color = " + this.color);
}
}
}
var cow = new Cow("cow", "black");
cow.showInfo();
var cow1 = new Cow("cow1", "black1");
cow1.showInfo();
</script>
</head>
<body>
</body>
</html>