博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
javascript中的继承
阅读量:4598 次
发布时间:2019-06-09

本文共 1744 字,大约阅读时间需要 5 分钟。

原型链模式和组合继承模式的区别就在于:继承模式中调用了两次基类的构造函数,结果实例中的属性就屏蔽了原型中的同名属性(这样做可以避免各个实例共享的引用实例相互影响)。组合继承是javascript中最常用的继承模式。

例如

View Code
1 function Person(name){ 2     this.name = name; 3     this.colors = ["red","blue","white"]; 4 } 5 Person.prototype.sayName = function(){ 6     return this.name; 7 } 8 function Student(name,age){ 9     Person.call(this,name);//组合模式中需要这句10     this.age = age;    11 }12 Student.prototype = new Person();13 Student.prototype.sayAge = function(){14     return this.age;15 }16 var student = new Student("fsdf",12);17 student.colors.push("black");18 19 alert(Student.prototype.colors);//red,blue,white20 alert(student.name);//fsdf21 alert(student.colors);//red,blue,white,black

寄生组合模式

View Code
1 function object(o){ 2    function F(){} 3    F.prototype = 0; 4    return new F();    5 } 6 function inheritPrototype(student,person){ 7    var prototype = object(person.prototype); 8    prototype.constructor = student; 9    student.prototype = prototype;   10 }11 function Person(name){12     this.name = name;13     this.colors = ["red","blue","white"];14 }15 Person.prototype.sayName = function(){16     return this.name;17 }18 function Student(name,age){19     Person.call(this,name);20     this.age = age;    21 }22 inheritPrototype(Student,Person);23 Student.prototype.sayAge = function(){24   alert(this.age);25 }26 var student = new Student("fsdf",12);27 student.colors.push("black");28 alert(Student.prototype.colors);//undefined29 alert(student.name);//fsdf30 alert(student.colors);//red,blue,white,black

比较两种模式,很容易发现在寄生组合模式中Student.prototype上面没有创建不必要的属性name和colors,从而提高了效率,同时原型链保持不变。开发人员普遍认为寄生组合式继承是引用类型最理想的继承方式。

YUI的YAHOO.lang.extend()方法采用的就是寄生组合继承。

转载于:https://www.cnblogs.com/lanse-yan/archive/2012/12/14/2818488.html

你可能感兴趣的文章
08. 删除重复&海量数据
查看>>
重新想象 Windows 8 Store Apps (71) - 其它: C# 调用 C++
查看>>
发布mvc遇到的HTTP错误 403.14-Forbidden解决办法
查看>>
记录一些好用的工具
查看>>
超链接样式设置(去下划线)(转)
查看>>
restcontroller和controller区别
查看>>
2016012003+陈琦+散列函数的应用及其安全性
查看>>
Android 状态栏通知Notification、NotificationManager详解
查看>>
Sublime Text 3中使用正则表达式删除空行
查看>>
UIApplicationDelegate协议
查看>>
再谈iOS 7的手势滑动返回功能
查看>>
Jmeter测试dubbo接口填坑
查看>>
python小练——找出指定目录下小于指定字节的文件,输出到文本文件
查看>>
渐渐磨砺--16年11月封闭总结
查看>>
[zz]GDB调试精粹及使用实例
查看>>
数据库的创建和删除
查看>>
【消息队列MQ】各类MQ比较
查看>>
最简单的三层实例【插入据
查看>>
设计模式学习笔记——Prototype原型模式
查看>>
pom.xml里有红叉报错的解决办法
查看>>