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

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

一、继承1、利用原型链实现继承function SuperFn(){	this.flag=true;}SuperFn.prototype.judgeFlag=function(){	console.log("this.flag",this.flag)}function suberFn(name){	this.flag=name}var s=new SuperFn()suberFn.prototype=s;优点:所有实例可以共享原型对象中的属性和方法缺点:如果原型对象中的属性是引言类型,会导致所有实例的更改(官方:如果包含引用类型值的原型属性会被所有实例共享)(它的优点也即是他的缺点)2、利用call方法实现继承(借用构造函数)function superName(name){  console.log("super")  this.name=name	}function subName(age){	console.log("suber")	superName.call(this)	this.age=age}superName.prototype.sayname=function(){  console.log("name==",this.name)}subName.prototype=new superName()subName.prototype.constructor=subName优点:在子类构造函数中可以向超类构造函数传递参数缺点:不能实现函数复用(超类原型对象中定义的属性和方法不能共享)3、组合式继承(将原型链和构造函数合在一起)function superType(name){	console.log("super")	this.name=name}function suberType(age){	console.log("suber")	superType.call(this,"lxx");  //第二次调用超类 superType	this.age=age}superType.prototype.sayname=function(){	console.log("name==",this.name)}suberType.prototype=new superType()  //第一次调用超类 superTypesuberType.prototype.constructor=suberType优点:可以共享原型对象的属性和方法,可以向超类传递参数缺点:不管什么情况下,都会两次调用超类构造函数4、利用Object.create实现继承var person={	name:'lxx',	age:23,	sex:1}var another=Object.create(person)function animal(){	this.say=true;}animal.prototype.sayname=function(){	console.log("name==",this.say)}var dog=Object.create(animal.prototype) //利用Object.create(animal.prototype)来实现及继承Object.create()方法MDN是上的标准解释是:Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__。 Tips: Object.create(null)可以创建一个没有任何原型的对象缺点:浏览器兼容问题,IE 9+,chorome,Safari 5+,Firefox 4+;5、利用class(es6)语法实现继承class Point {  constructor(x, y) {    this.x = x;    this.y = y;	return 3  }  toString() {    return '(' + this.x + ', ' + this.y + ')';  }}class colorPoint extends Point{	constructor(x,y,color){		super(x,y);		this.color=color	}}复制代码

转载地址:http://uwoll.baihongyu.com/

你可能感兴趣的文章
在SAP云平台的CloudFoundry环境下消费ABAP On-Premise OData服务
查看>>
加州无人驾驶汽车新规遭到多家汽车厂商反对
查看>>
CakePHP 2.10.16 发布,PHP 快速开发框架
查看>>
深入浅出话资源
查看>>
Akamai推出全新托管服务,助力在线企业应对多重网络性能挑战
查看>>
【重磅】中国AVS2标准被国际超高清联盟UHD Forum采纳,推荐给全球视频服务商
查看>>
神奇,教你用随机数打印hello world
查看>>
下一个风口:物联网!
查看>>
Memblaze亮相2016 OpenPOWER中国峰会 开放共赢是未来
查看>>
MongoDB之建立Windows和本地虚拟机的双向连接
查看>>
Elasticsearch 安装和后台运行(真实有效,Mac版本已经验证)
查看>>
一个逼格很低的appium自动化测试框架
查看>>
微软应用最遭贼惦记
查看>>
恒温锅在手,分子料理分分钟搞定
查看>>
Java基础常用API(转载)
查看>>
为什么说企业CMO必须关注区块链变革?
查看>>
Veeam成立十周年,展望未来十年的科技发展
查看>>
xcode中嵌入framework(接入快用最新SDK遇到的问题)
查看>>
从“祸从口出”的胖帕切入,看Oculus的VR发展之路
查看>>
区块链落地面临的关键问题及其解决方案
查看>>