function createPerson(name,sex,color) //构造函数 { var obj=new Object();//创建一个空对象 obj.name=name; obj.sex=sex; obj.color=color; obj.Showname=function() { alert("我的名字是"+this.name); }; obj.Showsex=function() { alert("我是"+this.sex+"的") }; obj.Showcolor=function() { alert("我喜欢的颜色是"+this.color) }; return obj; //返回对象 }; var k1=createPerson("nian","女","blue"); // k1.Showname(); k1.Showsex(); k1.Showcolor();
<script> //prototype方法 function Person(name,sex,friend,color) { this.name=name; this.sex=sex; this.fr=friend; this.color=color; }; Person.prototype.showName=function() { alert("我的名字叫"+this.name); }; Person.prototype.showSex=function() { alert("我是"+this.sex+"的噢"); }; Person.prototype.showfr=function() { alert("朋友"+this.fr+"nian"); }; Person.prototype.showColor=function() { alert("我喜欢"+this.color); }; var p=new Person("李美娜","女的","茉莉","这个蓝色") p.showName(); p.showSex(); p.showfr(); p.showColor(); </script>