【JavaScript 6连载】五、继承的概念

时间:2022-06-28 15:03:29

<!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>