设计模式——各种继承方式
2015-11-30 14:59
302 查看
一、原型继承
B.prototype=new A; 子类的原型等于父类的一个实例
把父类A中私有的属性和公有的属性都继承过来,变为子类B中公有的属性
二、call继承
在子类B的函数体中,把父类A当做普通函数执行,并且让父类A中的this变为子类B的一个实例,这样就相当于把父类A中的所有的私有的属性都增加给子类B的实例了
只能把A中私有的继承过来,当做B中私有的,公有属性的无法进行处理
三、冒充对象继承
在子类B的函数体中,先获取父类A的一个实例,然后遍历这个实例中的所有属性,把所有的属性依次赋值给子类B的实例的私有的属性
把A中公有的和私有的都变为了B中私有的
四、混合模式:原型模式+call模式
A中私有的在B中私有的和公有的都存在了,A中公有的在B中公有的
虽然A中私有的重复了,但是没有太大的影响,如果非要私有的就是私有的,公有的就是公有的,我们只需要自己在编写一个程序把私有的删掉即可
五、中间类继承:在IE下不兼容、我们一般用它只处理内置类
B.prototype=new A; 子类的原型等于父类的一个实例
把父类A中私有的属性和公有的属性都继承过来,变为子类B中公有的属性
function A() { this.x = 100; } A.prototype = { constructor: A, getX: function () { console.log(this.x); } }; function B() { this.y = 200; } B.prototype = new A; B.prototype.constructor = B;
二、call继承
在子类B的函数体中,把父类A当做普通函数执行,并且让父类A中的this变为子类B的一个实例,这样就相当于把父类A中的所有的私有的属性都增加给子类B的实例了
只能把A中私有的继承过来,当做B中私有的,公有属性的无法进行处理
function A() { this.x = 100; } A.prototype = { constructor: A, getX: function () { console.log(this.x); } }; function B() { this.y = 200; A.call(this);//-->A.call(b) } var b = new B;
三、冒充对象继承
在子类B的函数体中,先获取父类A的一个实例,然后遍历这个实例中的所有属性,把所有的属性依次赋值给子类B的实例的私有的属性
把A中公有的和私有的都变为了B中私有的
function A() { this.x = 100; } A.prototype = { constructor: A, getX: function () { console.log(this.x); } }; function B() { this.y = 200; var temp = new A; for (var key in temp) { if (key !== "constructor") { this[key] = temp[key]; } } // this.temp = new A; // for (var key in this.temp) { // if (key !== "constructor") { // this[key] = this.temp[key]; // } // } // delete this.temp; } var b = new B; console.dir(b);
四、混合模式:原型模式+call模式
A中私有的在B中私有的和公有的都存在了,A中公有的在B中公有的
虽然A中私有的重复了,但是没有太大的影响,如果非要私有的就是私有的,公有的就是公有的,我们只需要自己在编写一个程序把私有的删掉即可
function A() { this.x = 100; } A.prototype = { constructor: A, getX: function () { console.log(this.x); } }; function B() { this.y = 200; A.call(this); } B.prototype = new A; B.prototype.constructor = B; //将B公有中继承了A私有的删除掉,以下可以不写,除非你有强迫症 B.prototype.delPrivate = (function () { var a = new A; for (var key in this) { if (a.hasOwnProperty(key)) { delete this[key]; } } return null; }).call(B.prototype); var b = new B; console.dir(b);
五、中间类继承:在IE下不兼容、我们一般用它只处理内置类
function sum() { arguments.__proto__ = Array.prototype; arguments.sort(function (a, b) { return a - b; }); return arguments; } console.log(sum(12, 23, 15, 23, 14, 15, 16, 10));
相关文章推荐
- lexical_cast
- JavaScript与jQuery获取相邻控件
- 黑马程序员—Java基础—IO流—字节流
- docker 容器故障导致无法启动解决办法
- beyond compare 中文乱码问题解决方法
- postgresql dead_tuple和live_tuple
- JavaScript与jQuery获取相邻控件
- JavaScript与jQuery获取相邻控件
- JavaScript与jQuery获取相邻控件
- Android 手机存储目录详解
- android gradle dependencies
- FrameLayout布局(1)
- 设计模式——工厂三姐妹
- 系统后台框架
- ip地址的正则表达式
- Linux的cron和crontab
- 在map中保存struct,及map的文件输入输出
- SQL中inner join、outer join和cross join的区别
- iBATIS与Hibernate的区别
- linux 统计grep 后的行数 wc