/*
* function: inherit -> 通过圣杯模式来实现继承
* params:
* Target:继承的对象
* Origin: 被继承的对象
*/
function inherit(Target, Origin) {
// careate a buffer function
function Buffer() {
}
// let the prototype of Buffer point to the instance of Origin
Buffer.prototype = Origin.prototype
// let the prototype of Target point to the instance of Buffer
Target.prototype = new Buffer()
// rewrite the constructor
Target.prototype.construtor = Target
// set the superclass
Target.prototype.super_class = Origin
}
function Teacher(){
}
// 设置原型上的属性
Teacher.prototype.name = "zhangsan"
function Student(){
}
// 调用函数来实现继承
inherit(Student, Teacher)
var s = new Student()
s.age = 18
console.log(s);
console.log(s.name); // zhangsan
console.log(s.age); // 18
可以看到成功实现了继承,同时Student的原型上的constructor属性值为 Student,而super_class 属性的值为 Teacher。