为JavaScript所有对象添加一个继承方法
本继承方法仍然是基于JavaScript原型属性来实现的.
Function.prototype.inherit = function(parent){
this.prototype = Object.create(parent.prototype);
this.prototype.constructor = this;
};本方法扩展到Function对象上,目的是让JavaScript中所有的构造函数都拥有此方法.
参数说明:
* parent: 被继承的父类构造函数.
用法示例如下:
Function.prototype.inherit = function(parent){
this.prototype = Object.create(parent.prototype);
this.prototype.constructor = this;
};
function People(name,age){
this.name = name;
this.age = age;
}
People.prototype = {
getName:function(){
return this.name;
},
say:function(){
console.log("hello");
}
};
function Student(name,age,id){
People.call(this,name,age);
this.id = id;
}
Student.inherit(People);
Student.prototype.getId = function(){
return "this id is " + this.id;
};
var s = new Student("Jhon",22,3.1415926);
console.log(s.getName());
console.log(s.say());
console.log(s.getId());
console.log(s.constructor);