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.aaa 18 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>
时间: 2024-12-28 00:09:46