在JavaScript中用构造函数创建对象.
function Stu(){ this.name="stu"; this.age=19; }创建出的对象全是不一样的个体,意味着每个个体里的属性,方法也是不一样的,占用着不一样的空间. 而每个个体里的方法都是一样,这非常消耗内存和空间. prototype是属于构造函数的属性,每个构造函数都有一个原型(prototype),所有该构造函数创建的实例都共享一个prototype空间.(无论是添加前创建的还是添加后创建的)
<script> function Stu(name,age){ this.name=name; this.age=age; } var a=new Stu(); Stu.prototype.id=0; var b=new Stu(); document.write(a.id);//0 document.write(b.id);//0 </script>因为prototype是所有实例共享的,所以通过实例是不能修改prototype内的属性,只能在自己的空间添加一个同名的属性.而调用时调用自己空间的属性.如果自己体内找不到那个属性则再到prototype内找.
<script> function Stu(name,age){ this.name=name; this.age=age; } var a=new Stu(); a.id=1; document.write(a.id);//1 Stu.prototype.id=0; var b=new Stu(); a.id=2 document.write(a.id);//2 document.write(b.id);//0 </script>