javascript原型繼承
阿新 • • 發佈:2018-07-13
com png == 函數 hello prototype 封裝 橋接 方法
用一張圖來表示新的原型鏈:
封裝一個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; // true xiaoming.__proto__.__proto__ === Student.prototype; // true // 驗證繼承關系: xiaoming instanceof PrimaryStudent; // true xiaoming instanceofStudent; // true
原型繼承 - 廖雪峰的官方網站 (選自 @廖雪峰)
https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/0014344997013405abfb7f0e1904a04ba6898a384b1e925000
javascript原型繼承