[关闭]
@ruoli 2017-04-07T07:16:57.000000Z 字数 822 阅读 1268

JavaScript 面向对象

Web前端


  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>面向对象Js</title>
  6. <script type="text/javascript">
  7. // 父类
  8. (function(){
  9. var n=123; //此属性 仅供 People类访问,外部无法访问
  10. function People(name){//构造方法,此处定义 People类
  11. this._name=name;
  12. }
  13. People.prototype.say = function(){ //为 People类 新增一个say方法
  14. alert("People-Hello "+this._name+" - "+n);
  15. }
  16. window.People=People; // People类 默认外部是不可调用的,此处暴露给window对象,使外部可以直接调用。
  17. }());
  18. // 子类
  19. (function(){
  20. function Student(name){ //定义类 Student
  21. this._name=name;
  22. }
  23. Student.prototype=new People();//继承父类 People
  24. var superSay=Student.prototype.say; //获取父类的 say方法
  25. Student.prototype.say=function(){ //子类重写父类的 say方法
  26. superSay.call(this);//子类中调用父类的方法
  27. alert("Student-Hello "+ this._name);
  28. }
  29. window.Student=Student; //将 Student 类暴露给 外部
  30. }());
  31. var student=new Student("ruoli"); // new 一个 Student 类的 对象
  32. student.say(); //调用 student 对象的 say 方法
  33. </script>
  34. </head>
  35. <body>
  36. </body>
  37. </html>
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注