首页 > 代码库 > JavaScript中的对象冒充

JavaScript中的对象冒充

JavaScript里没有继承关键字,想要继承一个类需要用到“对象冒充”。

 

 1 <!DOCTYPE html> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5     <title>对象冒充</title> 6 </head> 7 <body> 8     <script type="text/javascript"> 9         function Animal(name, age) {10             this.name = name;11             this.age = age;12             this.shout = function () {13                 alert("嘎嘎!");14             }15         }16         function Dog(name, age) {17             //把Animal构造函数赋给this.aaa18             this.aaa = Animal;19             //运行调用!!20             this.aaa(name,age);21         }22         var dog = new Dog("小黑", 3);23         alert(dog.name);24         //方法也能继承25         dog.shout();26     </script>27 </body>28 </html>

 

JavaScript中的对象冒充