深入理解js——构造函数的继承
看了阮一峰的网络日志(http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_inheritance.html),记录一下构造函数继承的几种方式。
1、构造函数绑定
使用call或apply方法,将父对象的构造函数绑定在子对象上,即在子对象构造函数中加一行:Parent.apply(Child, arguments);
2、使用prototype模式
第一步(删除Child的prototype 对象原先的值,赋予一个新值):Child.prototype = new Parent();
第二步(Child的原型的构造器指向Child):Child.prototype.constructor = Child;
3、直接继承prototype
Child.prototype = Parent.prototype;
Child.prototype.constructor = Child;
4、利用空对象作为中介
function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.uber = Parent.prototype;
}
5、拷贝继承
第一步:把Parent的所有不变属性,都放到它的prototype对象上。
第二步:将父对象的prototype对象中的属性,一一拷贝给Child对象的prototype对象。
function extend(Child, Parent) {
var p = Parent.prototype;
var c = Child.prototype;
for (var i in p) {
c[i] = p[i];
}
c.uber = p;
}
最新文章
- location.href 一个小注意
- 使用ab进行页面的压力测试
- iOS开发——项目篇—高仿百思不得姐 05——发布界面、发表文字界面、重识 bounds、frame、scrollView
- tomcat发布记录
- CSharp 调用存储过程来执行增、删、改操作
- 【HTML5 4】《HTML5与CSS3权威指南》 step1 导读
- Minicom配置及使用详解
- SUSE linux 使用LVM安装系统和管理
- SQL写操作 设置内容 (数组转字符串)
- LeetCode 153. Find Minimum in Rotated Sorted Array (在旋转有序数组中找到最小值)
- Delphi indy线程控件TIdThreadComponent的使用
- for each ;for in;for of 三者的区别
- url两次编码
- centos 终端界面代理设置
- The XOR Largest Pair(Tire字典树应用)
- MySQL Cluster
- TListBox的项目个数
- Jenkins搭建.NET自动编译发布远程环境
- 在 Linux redis 验证交互连接过程中遇到 redis Could not connect to Redis at 127.0.0.1:6379: Connection refused 的解决方法
- maven仓库中添加自定义的包jar包