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

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

1. 使用对象冒充实现继承

function Person(username){    this.username=username;    this.sayHello=function(){        alert(this.username);    }}function Child(username,password){    this.superUserName=Person;    this.superUserName(username);    delete this.superUserName;        this.sayWord=function(){        alert(password);    }}var a=new Person('a');a.sayHello();var b=new Child('b','2b');b.sayHello();b.sayWord();

2. 使用Function的call方法

function Person(username){    this.username=username;    this.sayHello=function(){        alert(this.username);    }}function Child(username,password){    Person.call(this,username);        this.sayWord=function(){        alert(password);    }}var a=new Person('a');a.sayHello();var b=new Child('b','2b');b.sayHello();b.sayWord();

3.使用Function的apply方法

function Person(username){    this.username=username;    this.sayHello=function(){        alert(this.username);    }}function Child(username,password){    Person.apply(this,[username]);        this.sayWord=function(){        alert(password);    }}var a=new Person('a');a.sayHello();var b=new Child('b','2b');b.sayHello();b.sayWord();

4.原型方式实现继承(无法实现参数传递)

function Person(){}Person.prototype.username='hello';Person.prototype.sayHello=function(){    alert(this.username);}function Child(){    }Child.prototype=new Person();Child.prototype.password='word';Child.prototype.sayWord=function(){    alert(this.password);}var a=new Person();a.sayHello();var b=new Child();b.sayHello();b.sayWord();

5.原型混合方式实现继承

function Person(username){    this.username=username;}Person.prototype.sayHello=function(){    alert(this.username);}function Child(username,password){    this.password=password;    Person.call(this,username);}Child.prototype=new Person();Child.prototype.sayWord=function(){ //放在new Person后面,不然会被覆盖    alert(this.password);}var a=new Person('a');a.sayHello();var b=new Child('b','2b');b.sayHello();b.sayWord();

 

转载于:https://www.cnblogs.com/BigIdiot/archive/2013/03/01/2938241.html

你可能感兴趣的文章
iOS多线程NSOperation篇
查看>>
关于B站的弹幕集成
查看>>
本人开源项目 Lu-Rpc
查看>>
echart地图使用经验-地图变形和添加数据
查看>>
牵引力教育告诉你,自学设计的学员为什么90%都学不会?
查看>>
Teambition X 2019 校招
查看>>
使用Puppeteer轻松爬取网易云音乐、QQ音乐的精品歌单
查看>>
高并发-「抢红包案例」之一:SSM环境搭建及复现红包超发问题
查看>>
iOS 多国语言本地化与App内语言切换(Swift)
查看>>
window下git多账户管理
查看>>
阿里云服务器部署LAMP
查看>>
使用jMeter构造大量并发的随机HTTP请求
查看>>
做一个帮你快速调试UI参数的Android插件
查看>>
经典的 Top K 问题,你真的懂了么?
查看>>
ionic3 相机和相册获取图片
查看>>
JavaScript 基础(2)- 操作符、字符串、数组
查看>>
Spark log4j 日志配置详解
查看>>
Java学习:JVM是什么?
查看>>
深度解析国内首个云原生数据库POLARDB的“王者荣耀”
查看>>
常见乱码问题分析和总结
查看>>