|
JavaScript里没有继承关键字,想要继承一个类需要用到“对象冒充”。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>对象冒充</title>
</head>
<body>
<script type="text/javascript">
function Animal(name, age) {
this.name = name;
this.age = age;
this.shout = function () {
alert("嘎嘎!");
}
}
function Dog(name, age) {
//把Animal构造函数赋给this.aaa
this.aaa = Animal;
//运行调用!!
this.aaa(name,age);
}
var dog = new Dog("小黑", 3);
alert(dog.name);
//方法也能继承
dog.shout();
</script>
</body>
</html>注:对象冒充可以支持多重继承,也就是说一个类可以继承多个类. 参考:http://www.cnblogs.com/Jacklovely/p/5909902.html 更多详情:https://www.cnblogs.com/libin-1/p/7087605.html |
|
|