日期:2014-05-16 浏览次数:20363 次
<script type="text/javascript"> function createPerson(name,age) { var obj = new Object(); obj.name = name; obj.age = age; obj.say = function() { alert(this.name+","+this.age); } return obj; } //无法检测对象p1和p2的数据类型 var p1 = createPerson("aa",22); var p2 = createPerson("bb",33); p1.say(); p2.say(); </script>
<script type="text/javascript"> function Person(name,age){ this.name = name; this.age = age; this.say = say; this.sayHello = function(){ alert(this.name + ":" + this.age); } } function say(){ alert(this.name + ":" + this.age); } var p1 = new Person("a",1); var p2 = new Person("b",2); alert(p1.sayHello == p2.sayHello);//false alert(p1.say == p2.say);//true </script>
<script type="text/javascript"> //通过原型方式创建对象 function Person(){ } Person.prototype.name = "ztchen"; Person.prototype.age = 24; Person.prototype.getInfo = function(){ alert(this.name + ";" + this.age); } var p1 = new Person(); var p2 = new Person(); p1.name = "lishi"; p1.getInfo();//打印lishi:24 p2.getInfo();//打印ztchen:24 </script>
<script type="text/javascript"> //通过原型 + 构造函数方式创建对象 function Person(name,age,friends){ this.name = name; this.age = age; this.friends = friends; } Person.prototype.getInfo = function(){ alert(this.name + ";[" + this.friends + "]"); } var p1 = new Person("ztchen",24,["aa","bb"]); var p2 = new Person("lishi",24,["cc","dd"]); p1.friends.push("tt"); p2.friends.push("yy"); p1.getInfo();//打印ztchen:[aa,bb,tt] p2.getInfo();//打印lishi:[cc,dd,yy] alert(p1.getInfo == p2.getInfo);//打印true </script>
<script type="text/javascript"> //通过动态原型方式创建对象 function Person(name,age,friends){ this.name = name; this.age = age; this.friends = friends; //判断Person.prototype.getInfo是否存在,若存在就不会创建 if(!Person.prototype.getInfo){ Person.prototype.getInfo = function(){ alert(this.name + ";[" + this.friends + "]"); } } } var p1 = new Person("ztchen",24,["aa","bb"]); var p2 = new Person("lishi",24,["cc","dd"]); p1.friends.push("tt"); p2.friends.push("yy"); p1.getInfo();//打印ztchen:[aa,bb,tt] p2.getInfo();//打印lishi:[cc,dd,yy] alert(p1.getInfo == p2.getInfo); </script>