<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>继承</title>
</head>
<body>
<script type="text/javascript">
// 利用对象冒充实现 函数继承
function ClassA(sColor) {
this.color = sColor;
this.sayColor = function () {
alert(this.color);
};
}
ClassA.prototype.red = function(aa){
console.log(aa)
}
function ClassY() {
this.load = function () {
alert("loading");
};
}
function ClassB(sColor, sName) {
this.newMethod = ClassA;
this.newMethod(sColor);
// 删除此属性 确保其只执行一次,避免出现bug
delete this.newMethod;
// 多继承
this.newMe = ClassY;
this.newMe();
// 删除此属性 确保其只执行一次,避免出现bug
delete this.newMe;
this.name = sName;
this.sayName = function () {
alert(this.name);
};
}
ClassB.prototype=ClassA.prototype;
var objA = new ClassA("blue");
var objB = new ClassB("red", "John");
objA.sayColor(); //输出 "blue"
objB.sayColor(); //输出 "red"
objB.sayName(); //输出 "John"
objB.load(); //输出 "John"
objB.red("aaaaaaa")
// 利用call实现继承
function ClassZ(sColor,sName){
ClassA.call(this,sColor)
this.name = sName;
this.sayName = function () {
alert(this.name);
};
}
</script>
</body>
</html>