prototype

prototype是js实现代码共享,继承的利器.

1 共享

 1 var Person = function(name){
 2     this.name = name;
 3 }
 4 Person.prototype.pName = function(){
 5    alert(this.name);  
 6 }
 7 
 8 var p1 = new Person();
 9 var p2 = new Person();
10 alert(p1.pName === p2.pName); //true

   细节:

    1 new Person() 相当于

                  var obj = {};  //创建一个新对象

                  obj.__proto__ = Person.prototype;   //把函数的prototype属性赋给新对象的原型属性

                  Person.call(obj);

     2 p1.pName 执行时, 先去p1对象本身找方法,如没有则到__proto__属性找

 

2 继承

 

 1 var Person = function(name){
 2     this.name = name;
 3 }
 4 Person.prototype.pName = function(){
 5     alert(this.name);  
 6 }
 7  
 8 var Student = function(name,score){
 9     Person.pName.call(this,name);
10     this.score = score;          
11 }
12 Student.prototype = new Person();
13 
14 var stu = new Student("stu");
15 stu.pName(); //stu

 

细节:

    1, 12行,把Student.prototype的设为Person对象,该对象的__proto__属性有pName方法

    2,  stu.pName 执行时, 在找对象本身此方法,没有 -> stu.__proto__(此时为Person对象),没有 -> Person().__proto__,找到

最终通过对象prototype链实现了继承

 

总结:

1 无new不谈prototype

2 构造函数创造了原型链

 

 

 

 

 

posted @ 2014-02-07 22:50  _SharpCode  阅读(164)  评论(0编辑  收藏  举报