原型链以及继承

来源:互联网 发布:推推棒淘宝店 编辑:程序博客网 时间:2024/06/06 11:00

原型链

原型链是实现继承的主要方法,基本思想是利用原型让一个引用类型(Object,Array等)继承另一个引用类型的属性和方法。

基本模式如下:

<script>function Father(){this.property = true;};Father.prototype.getPro = function(){return this.property;};function Son(){this.subproperty = false;};//继承了FatherSon.prototype = new Father();var person = new Son();console.log(person.getPro());  //true</script>

在通过原型链实现继承时,不能使用对象字面量创建原型方法,这样会重写原型链。

//继承了FatherSon.prototype = new Father();//使用字面量添加方法 会导致上一条代码无效Son.prototype = {getSub : function(){return this.subproperty;}};var person = new Son();console.log(person.getPro()) //errors

原型链的问题

包含引用类型值的原型属性会被所有实例共享。


经典继承:

<script>function Father(){this.num = [1,2,3,4];};function Son(){//继承了 FatherFather.call(this); };var person1 = new Son();person1.num.push(5);alert(person1.num);  //1,2,3,4,5var person2 = new Son();person2.num.push(6);alert(person2.num)  //1,2,3,4,6</script>


组合继承:

<script>function Father(name){this.name = name;this.num = [1,2,3,4];};Father.prototype.sayName = function(){alert(this.name);};function Son(name,age){//继承属性Father.call(this,name);this.age = age; };//继承方法Son.prototype = new Father();Son.prototype.constructor = Son;Son.prototype.sayAge = function(){alert(this.age);};var person1 = new Son('gao',22);person1.num.push(5);alert(person1.num);   //1,2,3,4,5person1.sayName();    //gaoperson1.sayAge();     //22var person2 = new Son('liang',23);person2.num.push(6);alert(person2.num);    //1,2,3,4,6person2.sayName();   //liangperson2.sayAge();   // 23</script>


原型式继承: 

借助原型可以基于已有的对象创建新对象(必须有一个对象可以作为另一个对象的基础)

使用 Object.create()

<script>var person = {name:'gao',age:[1,2,3]};var person1 = Object.create(person);person1.age.push(4);var person2 = Object.create(person);person2.age.push(5);console.log(person.age);  //1,2,3,4,5</script>

  Object.create()返回了一个新对象(person1,person2) ,将person作为原型,新对象的原型中包含引用类型值和基本类型值,所以 age属性会被person1 person2 共享,相当于创建了2个person对象的副本。


总结于JavaScript高级程序设计

原创粉丝点击