首页 > 语言 > JavaScript > 正文

JavaScript中继承用法实例分析

2024-05-06 16:20:26
字体:大 中 小
来源:转载
供稿:网友

这篇文章主要介绍了JavaScript中继承用法,以实例形式较为详细的分析了javascript实现继承的相关技巧,需要的朋友可以参考下

本文实例分析了JavaScript中继承的用法。分享给大家供大家参考。具体如下:

 

 
  1. // define the Person Class 
  2. function Person() {} 
  3. Person.prototype.walk = function(){ 
  4. alert ('I am walking!'); 
  5. }; 
  6. Person.prototype.sayHello = function(){ 
  7. alert ('hello'); 
  8. }; 
  9. // define the Student class 
  10. function Student() { 
  11. // Call the parent constructor 
  12. Person.call(this); 
  13. } 
  14. // inherit Person 
  15. Student.prototype = new Person(); 
  16. // correct the constructor pointer because it points to Person 
  17. Student.prototype.constructor = Student; 
  18. // replace the sayHello method 
  19. Student.prototype.sayHello = function(){ 
  20. alert('hi, I am a student'); 
  21. } 
  22. // add sayGoodBye method 
  23. Student.prototype.sayGoodBye = function(){ 
  24. alert('goodBye'); 
  25. } 
  26. var student = new Student(); 
  27. student.sayHello(); 
  28. student.walk(); 
  29. student.sayGoodBye(); 
  30. // check inheritance 
  31. alert(student instanceof Person); // true  
  32. alert(student instanceof Student); // true 

希望本文所述对大家的javascript程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选