加载中...
原型继承
发表于:2021-07-10 | 分类: 前端 js 笔记
字数统计: 339 | 阅读时长: 1分钟 | 阅读量:

继承


继承的含义:

继承是面向对象编程中的一个重要概念,通过继承可以使子类的实例使用在父类中定义的属性和方法。

在js中是如何实现继承的呢?

由于本人技术有限目前只知道两种继承(组合继承,和es6的继承)

组合继承

// 父构造函数
			function Demo(name, age) {
				this.name = name;
				this.age = age;
				this.sing = function() {
					console.log('我会唱歌');
					console.log('我会跳迪斯科');
				}
			}
			//通过子类的原型继承父类的方法
			Jc.prototype = new Demo();
			//指回原来的构造函数
			Jc.prototype.constructor = Jc;
			//用call()方法实现了从父类继承属性和方法
			function Jc(name, age, tw) {
				this.tw = tw;
				Demo.call(this, name, age);
			}
			var ldh = new Jc('张三', 18, '迪斯科');
			console.log(ldh)
			console.log(Jc.prototype.constructor);
			ldh.sing();

这种继承方式有个缺点就是在继承父类函数的时候调用了父类构造函数,导致子类的原型上多了不需要的父类属性,存在内存上的浪费。

利用class

class Numbear {
			constructor(x, y) {
				this.x = x;
				this.y = y;
			}
			sum() {
				var sex = this.x + this.y
				console.log(sex);
			}
		}
		class Num extends Numbear {
			constructor(x, y) {
				super(x, y);
				this.x = x;
				this.y = y;
			}
			result() {
				var sex = this.x - this.y;
				console.log(sex);
			}
		}
		var son = new Num(10, 6);
		son.sum();
		son.result()
上一篇:
es5新增方法
下一篇:
js的原型、构造函数、原型链
本文目录
本文目录