20 继承

继承
     能继承什么东西:
		构造函数、以及原型中的所有东西
     原型继承实现方式就是:
		1、定义新的构造函数,并在内部用call()调用希望“继承”的构造函数,并绑定this;(仅需继承构造函数时需要)
		2、借助中间函数F实现原型链继承,最好通过封装的inherits函数完成;
		3、继续在新的构造函数的原型上定义新方法。

      有原型对象时继承
		Object.create()方法可以传入一个原型对象,并创建一个基于该原型的新对象,但是新对象什么属性都没有,因此,我们可以编写一个函数来创建xiaoming
		// 原型对象:
		var Student = {
			name: 'Robot',
			height: 1.2,
			run: function () {
				console.log(this.name + ' is running...');
			}
		};

		function createStudent(name) {
			// 基于Student原型创建一个新对象:
			var s = Object.create(Student);
			// 初始化新对象:
			s.name = name;
			return s;
		}

		var xiaoming = createStudent('小明');
		xiaoming.run(); // 小明 is running...
		xiaoming.__proto__ === Student; // true

         仅有构造函数时继承
  修改原型链上的继承关系
		function inherits(Child, Parent) {
			var F = function () {};
			F.prototype = Parent.prototype;
			Child.prototype = new F();
			Child.prototype.constructor = Child;
		}
		
		function Student(props) {
			this.name = props.name || 'Unnamed';
		}

		Student.prototype.hello = function () {
			alert('Hello, ' + this.name + '!');
		}

		function PrimaryStudent(props) {
			Student.call(this, props);
			this.grade = props.grade || 1;
		}

		// 实现原型继承链:
		inherits(PrimaryStudent, Student);

		// 绑定其他方法到PrimaryStudent原型:
		PrimaryStudent.prototype.getGrade = function () {
			return this.grade;
		};
class继承
	一个class:
		class Student {
				constructor(name) {
					this.name = name;
				}

				hello() {
					alert('Hello, ' + this.name + '!');
				}
			}
	class继承:
	class PrimaryStudent extends Student {
			constructor(name, grade) {
				super(name); // 记得用super调用父类的构造方法!
				this.grade = grade;
			}

			myGrade() {
				alert('I am at grade ' + this.grade);
			}
		}

  

  

原文地址:https://www.cnblogs.com/xuanjian-91/p/10998056.html