標籤:=== lan 官方網站 var parent 技術 cti his struct
用一張圖來表示新的原型鏈:
封裝一個inherits()函數,函數F用於橋接
function inherits(Child, Parent) { var F = function () {}; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child;}
這樣inherits()函數就可以重複使用了
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;};// 建立xiaoming:var xiaoming = new PrimaryStudent({ name: ‘小明‘, grade: 2});xiaoming.name; // ‘小明‘xiaoming.grade; // 2// 驗證原型:xiaoming.__proto__ === PrimaryStudent.prototype; // truexiaoming.__proto__.__proto__ === Student.prototype; // true// 驗證繼承關係:xiaoming instanceof PrimaryStudent; // truexiaoming instanceof Student; // true
原型繼承 - 廖雪峰的官方網站 (選自 @廖雪峰)
https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/0014344997013405abfb7f0e1904a04ba6898a384b1e925000
javascript原型繼承