标签:
1 <script> 2 function Parent(){ 3 this.name = ‘mike‘; 4 } 5 6 function Child(){ 7 this.age = 12; 8 } 9 Child.prototype = new Parent();//Child继承Parent,通过原型,形成链条 10 11 var test = new Child(); 12 alert(test.age); 13 alert(test.name);//得到被继承的属性 14 //继续原型链继承 15 function Brother(){ //brother构造 16 this.weight = 60; 17 } 18 Brother.prototype = new Child();//继续原型链继承 19 var brother = new Brother(); 20 alert(brother.name);//继承了Parent和Child,弹出mike 21 alert(brother.age);//弹出12 22 </script>
1 <script> 2 function Parent(age){ 3 this.name = [‘mike‘,‘jack‘,‘smith‘]; 4 this.age = age; 5 } 6 7 function Child(age){ 8 Parent.call(this,age); 9 } 10 var test = new Child(21); 11 alert(test.age);//21 12 alert(test.name);//mike,jack,smith 13 test.name.push(‘bill‘); 14 alert(test.name);//mike,jack,smith,bill 15 </script>
1 <script> 2 function obj(o){ 3 function F(){} 4 F.prototype = o; 5 return new F(); 6 } 7 var box = { 8 name : ‘trigkit4‘, 9 arr : [‘brother‘,‘sister‘,‘baba‘] 10 }; 11 var b1 = obj(box); 12 alert(b1.name);//trigkit4 13 14 b1.name = ‘mike‘; 15 alert(b1.name);//mike 16 17 alert(b1.arr);//brother,sister,baba 18 b1.arr.push(‘parents‘); 19 alert(b1.arr);//brother,sister,baba,parents 20 21 var b2 = obj(box); 22 alert(b2.name);//trigkit4 23 alert(b2.arr);//brother,sister,baba,parents 24 </script>
原型式继承首先在obj()
函数内部创建一个临时性的构造函数 ,然后将传入的对象作为这个构造函数的原型,最后返回这个临时类型的一个新实例。
标签:
原文地址:http://www.cnblogs.com/smart-tian/p/4621346.html