JS实现继承
来源:互联网 发布:java安装 错误1603 编辑:程序博客网 时间:2024/06/05 17:20
1.使用对象冒充实现继承(该种实现方式可以实现多继承)
实现原理:让父类的构造函数成为子类的方法,然后调用该子类的方法,通过this关键字给所有的属性和方法赋值
function Parent(firstname) { this.fname=firstname; this.age=40; this.sayAge=function() { console.log(this.age); } } function Child(firstname) { this.parent=Parent; this.parent(firstname); delete this.parent; this.saySomeThing=function() { console.log(this.fname); this.sayAge(); } } var mychild=new Child("李"); mychild.saySomeThing();
2.采用call方法改变函数上下文实现继承(该种方式不能继承原型链,若想继承原型链,则采用5混合模式)
实现原理:改变函数内部的函数上下文this,使它指向传入函数的具体对象
function Parent(firstname) { this.fname=firstname; this.age=40; this.sayAge=function() { console.log(this.age); } } function Child(firstname) { this.saySomeThing=function() { console.log(this.fname); this.sayAge(); } this.getName=function() { return firstname; } } var child=new Child("张"); Parent.call(child,child.getName()); child.saySomeThing();
3.采用Apply方法改变函数上下文实现继承(该种方式不能继承原型链,若想继承原型链,则采用5混合模式)
实现原理:改变函数内部的函数上下文this,使它指向传入函数的具体对象
function Parent(firstname) { this.fname=firstname; this.age=40; this.sayAge=function() { console.log(this.age); } } function Child(firstname) { this.saySomeThing=function() { console.log(this.fname); this.sayAge(); } this.getName=function() { return firstname; } } var child=new Child("张"); Parent.apply(child,[child.getName()]); child.saySomeThing();
4.采用原型链的方式实现继承
实现原理:使子类原型对象指向父类的实例以实现继承,即重写类的原型,弊端是不能直接实现多继承
function Parent() { this.sayAge=function() { console.log(this.age); } } function Child(firstname) { this.fname=firstname; this.age=40; this.saySomeThing=function() { console.log(this.fname); this.sayAge(); } } Child.prototype=new Parent(); var child=new Child("张"); child.saySomeThing();
0 0
- js继承如何实现继承?
- js中的继承实现
- js中的继承实现
- JS中的继承实现
- js中的继承实现
- js继承机制实现
- js如何实现继承
- JS继承的实现
- js实现继承机制
- js继承的实现
- js实现类继承
- js继承的实现
- js继承的实现
- js继承的实现
- JS中的继承实现
- js继承的实现
- js 继承实现
- js继承的实现
- 第十八章 认识系统服务
- 数据结构实验之二叉树五:层序遍历
- Git使用简介
- HTML特殊字符编码对照表
- DEBUG:javascript保持div的滚动条始终在最下面,解决scrollTop始终为0的问题
- JS实现继承
- 登录时保存用户cookies
- 使用Ajax的添加购物车
- 初学驱动开发-windows驱动-命令行编译环境
- count(*),count(1)和count(field)区别
- canvas知识体系
- 第四天if语句条件判断语句
- SDUT 3374 数据结构实验之查找二:平衡二叉树
- JAVAEE_springmvc+maven+batis