[JavaScript] JavaScript中使用继承的代码演示 →→→→→进入此内容的聊天室

来自 , 2020-09-25, 写在 JavaScript, 查看 225 次.
URL http://www.code666.cn/view/c28f6ae1
  1. // define the Person Class
  2. function Person() {}
  3.  
  4. Person.prototype.walk = function(){
  5.   alert ('I am walking!');
  6. };
  7. Person.prototype.sayHello = function(){
  8.   alert ('hello');
  9. };
  10.  
  11. // define the Student class
  12. function Student() {
  13.   // Call the parent constructor
  14.   Person.call(this);
  15. }
  16.  
  17. // inherit Person
  18. Student.prototype = new Person();
  19.  
  20. // correct the constructor pointer because it points to Person
  21. Student.prototype.constructor = Student;
  22.  
  23. // replace the sayHello method
  24. Student.prototype.sayHello = function(){
  25.   alert('hi, I am a student');
  26. }
  27.  
  28. // add sayGoodBye method
  29. Student.prototype.sayGoodBye = function(){
  30.   alert('goodBye');
  31. }
  32.  
  33. var student = new Student();
  34. student.sayHello();
  35. student.walk();
  36. student.sayGoodBye();
  37.  
  38. // check inheritance
  39. alert(student instanceof Person); // true
  40. alert(student instanceof Student); // true
  41. //javascript/5344

回复 "JavaScript中使用继承的代码演示"

这儿你可以回复上面这条便签

captcha