五种继承方式
来源:互联网 发布:解密算法 编辑:程序博客网 时间:2024/06/08 01:01
五种继承方式
1. 原型继承
function A() { this.x = 100;}A.prototype.getX = function () { console.log(this.x);};function B() { this.y = 200;}B.prototype = new Avar b = new B;console.log(b)
子类B想要继承父类A中的所有属性和方法(私有和公有),只需要让B.prototype=new A;
特点:它是把父类中私有的和公有的都继承到子类原型上
原型继承并不是把父类中的属性和方法克隆一份一模一样的给B,而是让B和A之间增加了原型链的连接,以后B的实例b想要A中的的getX方法,需要一级级的向上查找来使用,通过_ proto _子类可以改变父类的属性和方法
2. call继承
function B() { // this -> b A.call(this); // ->A.call(b) 把A执行让A中的this变为b}var b = new B;console.log(b.x) // 100console.log(b.getX()) // TypeError: b.getX is not a function
call继承把父类私有的属性和方法克隆一份一模一样的作为子类私有的属性
3. 冒充对象继承
function A() { this.x = 100;}A.prototype.getX = function () { console.log(this.x);};function B() { // this -> b var temp = new A; for (var key in temp) { this[key] = temp[key]; } temp = null;}var b = new B;console.log(b)
把父类的私有的和公有的克隆一份一模一样的给子类私有的
4. 混合模式继承
原理:原型继承+ call继承
function A() { this.x = 100;}A.prototype.getX = function () { console.log(this.x);};function B() { A.call(this) // -> n.x = 100}B.prototype = new A; // -> B.prototype: x=100,getXB.prototype.constructor = B;var b = new B;b.getX();
这种继承方式,会导致私有属性和公有属性重复
5.寄生组合式继承
私有的继承私有的(通过call)
公有的继承公有的(prototype上的继承prototype的,通过Object.create() )
function A() { this.x = 100;}A.prototype.getX = function () { console.log(this.x);};function B() { A.call(this)}B.prototype = Object.create(A.prototype);B.prototype.constructor = B;var b = new B;b.getX();
阅读全文
0 0
- 五种继承方式
- JavaScript五种继承方式
- JavaScript五种继承方式
- JavaScript五种继承方式
- JavaScript实现继承的五种方式
- javascript中实现对象继承的五种方式详解
- 学习记录--js中的五种继承方式
- js如何实现继承(js实现继承的五种方式)
- 黑马程序员--js如何实现继承(js实现继承的五种方式)
- js如何实现继承(js实现继承的五种方式)
- 启动线程的五种方式方法(通过继承Thread类或实现Runnable接口)
- 三种继承方式
- 三种继承方式
- 五种布局方式
- js五种继承方式(在别的博客上面看的,然后自己稍微整理一下)
- C++三种继承方式
- C++三种继承方式
- C++三种继承方式
- 人民日报凭栏处:做一条有梦想的咸鱼
- 关于CAN,讲得比较通俗易懂的一篇文章
- 15算法课程 83. Remove Duplicates from Sorted List
- java-return浅析
- 通信协议中的RTS与CTS
- 五种继承方式
- java高并发程序设计学习笔记一前言
- web前端缓存
- rabbitmq安装后,web管理端口http://localhost:15672/ 无法访问的解决
- javascript之(一)
- HDOJ 1019 Least Common Multiple
- 简单栈的数组实现
- 内联函数
- 如何从SD卡烧录文件到S5PV210