原型繼承
阿新 • • 發佈:2018-12-02
function Student(name) { this.name = name; this.hello = function () { alert('Hello, ' + this.name + '!'); } } // PrimaryStudent建構函式: function PrimaryStudent(props) { Student.call(this, props); this.grade = props.grade || 1; } // 空函式F: function F() { } // 把F的原型指向Student.prototype: // “建構函式F”和“建構函式Student”的prototype指向一個原型物件 F.prototype = Student.prototype;
把PrimaryStudent的原型指向一個F建構函式例項化的物件:
由於建構函式F的prototype指向了Stduent.prototype【建構函式Student的prototype屬性】所以由“建構函式F”構造的所有例項共享“建構函式Student”的原型屬性
PrimaryStudent.prototype = new F();
建構函式PrimaryStudent的原型現在是建構函式F()的一個例項,共享F()建構函式的原型物件,而F建構函式的原型與Student共享一個原型,所以建構函式PrimaryStudent構造的例項可以訪問Student的原型的所有屬性,構成了原型繼承
// 把PrimaryStudent原型的建構函式修復為PrimaryStudent: console.log(PrimaryStudent.prototype.constructor)//原本指向Student PrimaryStudent.prototype.constructor = PrimaryStudent; console.log(PrimaryStudent.prototype.constructor) // 繼續在PrimaryStudent原型(就是new F()物件)上定義方法: PrimaryStudent.prototype.getGrade = function () { return this.grade; };
// 建立xiaoming:
//構造一個例項xiaoming,xiaoming共享“建構函式PrimaryStudent”的原型F()
【PrimaryStudent.prototype = new F();】∵xiaoming是建構函式PrimaryStudent構造出來
PrimaryStudent.prototype是一個物件包含“建構函式PrimaryStudent”構造的所有例項共享的屬性
和方法。
而PrimaryStudent.prototype是一個物件,這個物件由“建構函式 F()”構造,所以這個物件共享建構函式
的prototype屬性,而建構函式F()的prototype和Student的prototype一樣。
var xiaoming = new PrimaryStudent({
name: '小明',
grade: 2
});
/
xiaoming.name; // '小明'
console.log(xiaoming.name)
xiaoming.grade; // 2
console.log(xiaoming.grade)
// 驗證原型:
xiaoming.__proto__ === PrimaryStudent.prototype; // true
console.log(xiaoming.__proto__ === PrimaryStudent.prototype)
xiaoming.__proto__.__proto__ === Student.prototype; // true
console.log(xiaoming.__proto__.__proto__ === Student.prototype)
// 驗證繼承關係:
xiaoming instanceof PrimaryStudent; // true
console.log(xiaoming instanceof PrimaryStudent)
xiaoming instanceof Student; // true
console.log(xiaoming instanceof Student)