原型使用的目的
共性对象的属性和方法
列:使用原型
<script type="text/javascript">
/*原型:共享对象的属性与方法
function Student(){}
Student.prototype.name='祖儿';
Student.prototype.age=23;
Student.prototype.eat=function(){
alert(this.name+" 吃东东");
}
var stu1=new Student();
var stu2=new Student();
alert(stu1.eat==stu2.eat) //方法的引用的地址是否保持一致呢?
*/
/*原型字面量的方式*/
function Student(){};
Student.prototype={
constructor:Student,
name:'老王',
age:22,
eat:function(){
return this.name+" 吃东西";
}
}
var stu1=new Student();
var stu2=new Student();
alert(stu1.eat==stu2.eat) //true,共享 结果:true
alert(stu1.constructor==Object) //默认是Object
alert(stu1.constructor==Student) //强制指向constructor:Student, 结果:true
//扩展功能:破坏封装...
String.prototype.addString=function(){
return this+" 222";
}
alert("小花".addString()) //结果:小花 2222
</script>