繼承 能繼承什麼東西: 構造函數、以及原型中的全部東西 原型繼承實現方式就是: 一、定義新的構造函數,並在內部用call()調用但願「繼承」的構造函數,並綁定this;(僅需繼承構造函數時須要) 二、藉助中間函數F實現原型鏈繼承,最好經過封裝的inherits函數完成; 三、繼續在新的構造函數的原型上定義新方法。 有原型對象時繼承 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); } }