父類
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype = {
eat:function(){
console.log(this.name+"正在吃飯...");
},
sang:function(){
console.log(this.name+"正在唱歌...");
}
}
var liuyu = new Person("劉雨", 26);
子類
function Student(name,age,score){
Person.call(this,name,age);
this.score = score;
}
封裝一個extends方法
//子類 extends 父類
Function.prototype.extends = function(func, options){
for(var key in func.prototype){
this.prototype[key] = func.prototype[key];
}
for(var name in options){
this.prototype[name] = options[name];
}
}
子類可以繼承父類的屬性和方法,也可以擴展自己的屬性和方法。extends方法參數:1.父類 2.需要擴展的屬性和對象的一個對象集合。
Student.extends(Person,{
study: function(){
console.log(this.name+"正在學習...");
}
});
var can = new Student("can",21,"良好");
can.eat();
can.study();