首页 > 其他 > 详细

prototype

时间:2014-02-08 00:59:32      阅读:383      评论:0      收藏:0      [点我收藏+]

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

1 共享

bubuko.com,布布扣
 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
bubuko.com,布布扣

   细节:

    1 new Person() 相当于

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

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

                  Person.call(obj);

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

 

2 继承

 

bubuko.com,布布扣
 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
bubuko.com,布布扣

 

细节:

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

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

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

 

总结:

1 无new不谈prototype

2 构造函数创造了原型链

 

 

 

prototype

原文:http://www.cnblogs.com/79home/p/3539950.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!