【JavaScript 6連載】五、繼承的概念
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>05-繼承的概念</title>
<script>
/*
function Dog (color,name){
this.skinColor = color;
this.name = name;
this.act = function (){
console.log(this.name + '汪汪汪');
}
}
function Person (color,name){
this.skinColor = color;
this.name = name;
this.act = function(){
console.log(this.name + '去遛狗');
}
}
var erha = new Dog('白色','二哈');
var xiaopao = new Person('黃色','小炮');
*/
// 重構上面的建構函式
// 定義一個父級建構函式
function Biology(color,name,fun){
this.skinColor = color;
this.name = name;
this.act = fun;
}
// 下面兩個建構函式通過apply和call方法來繼承上面建構函式Biology的屬性
function Dog(){
// 使用apply或者call方法呼叫Biology函式
Biology.apply(this,arguments);
}
var erha = new Dog('白色','二哈',function(){console.log(this.name + '汪汪汪');});
function Person(){
// 使用apply或者call方法呼叫Biology函式
Biology.call(this,arguments[0],arguments[1],arguments[2]);
this.job = arguments[3];
}
var xiaopao = new Person('黃色','小炮',function(){console.log(this.name + '散步');},'coder');
xiaopao.act();
// 物件的巢狀
xiaopao.pet = erha;
// 覆蓋act屬性
xiaopao.act = function(){
console.log(this.name + '和他的寵物' + this.pet.name + '一起去散步');
};
xiaopao.act();
// 物件巢狀,字面量
var erha2 = {
name:'二哈',
act:function(){
console.log(this.name + '汪汪汪');
}
}
var xiaohua = {
name:'小花',
pet:erha2,
act:function(){
console.log(this.name + '和他的寵物' + this.pet.name + '一起去散步');
}
}
xiaohua.act();
</script>
</head>
<body>
</body>
</html>