面向对象---prototype

构造函数里的this,外面的new

 1 <script>
 2 //用工厂方式构造对象
 3 function createPerson(name, sex)    //构造函数
 4 {
 5     //假想的系统内部工作流程
 6     //var this=new Object();
 7     this.name=name;
 8     this.sex=sex;
 9     
10     this.showName=function ()
11     {
12         alert('我的名字叫:'+this.name);
13     };
14     this.showSex=function ()
15     {
16         alert('我是'+this.sex+'的');
17     };
18     //假想的系统内部工作流程
19     //return this;
20 }
21 var p1=new createPerson('blue', '男');
22 var p2=new createPerson('leo', '女');
23 /*p1.showName();
24 p1.showSex();
25 p2.showName();
26 p2.showSex();*/
27 alert(p1.showName==p2.showName);
28 </script>

new出来的Object

类----这个东西类似于CSS里面的class,用来构造对象。类=构造函数

对象(实例)-----有自己的功能,被类构造出来

1 <script>
2 function show()
3 {
4     alert(this);
5 }
6 show();        //window
7 new show();    //新创建的对象
8 </script>

原型---解决了资源浪费,多次重复的创建对象的问题。

 1 <script>
 2 var arr1=new Array(12, 5, 8, 4);
 3 var arr2=new Array(44,6,5,4,5,55,9);
 4 //arr1.sum=function ()
 5 Array.prototype.sum=function ()
 6 {
 7     var result=0;
 8     var i=0;
 9     for(i=0;i<this.length;i++)
10     {
11         result+=this[i];
12     }
13     return result;
14 };
15 /*alert(arr1.sum());
16 alert(arr2.sum());*/
17 alert(arr1.sum==arr2.sum);
18 </script>

 构造函数+prototype

 1 <script>
 2 function Person(name, sex)//构造函数用来添加属性,属性是变化的
 3 {
 4     this.name=name;
 5     this.sex=sex;
 6 }
 7 Person.prototype.showName=function ()//原型用来添加方法,方法是不变的
 8 {
 9     alert(this.name);
10 };
11 Person.prototype.showSex=function ()
12 {
13     alert(this.sex);
14 };
15 var p=new Person('bee', '男');
16 p.showName();
17 p.showSex();
18 </script>

原型和对象方法的优先级

1 <script>
2 Array.prototype.a=12;
3 var arr=[1,2,3];
4 alert(arr.a);    //12
5 arr.a=5;
6 alert(arr.a);    //5,这个的优先级更高
7 delete arr.a;
8 alert(arr.a);    //12
9 </script>
posted @ 2013-06-17 12:15  Paxster  阅读(189)  评论(0编辑  收藏  举报