zoukankan      html  css  js  c++  java
  • 以一个最简单的例子把OO的JavaScript说明白

    .一个颇为精简的例子

    只需理解三个关键字:
    第一个是function ,JS世界里Class的定义用'function',function里面的内容就是构造函数的内容。
    第二个是this指针,代表调用这个函数的对象。
    第三个是prototype,用它来定义成员函数, 比较规范和保险。

    1. //定义Circle类,拥有成员变量r,常量PI和计算面积的成员函数area()   
    2. function Circle(radius)    
    3. {    
    4.     this.r = radius;   
    5. }   
    6.   
    7. Circle.PI = 3.14159;   
    8. Circle.prototype.area = function(){   
    9.     return Circle.PI * this.r * this.r;   
    10. }   
    11.   
    12. //使用Circle类   
    13. var c = new Circle(1.0);    
    14. alert(c.area());   

    另外成员函数定义还可以写成这样:

    1. function compute_area(){   
    2.     return Circle.PI * this.r * this.r;   
    3. }   
    4. Circle.prototype.area=compute_area;  

    2.继承

    注意两点
    1)定义继承关系 ChildCircle.prototype=new Circle(0); 其中0是占位用的
    2)调用父类的构造函数

    1. this.base=Circle;   
    2. this.base(radius);   
    3.   
    4. //定义ChildCircle子类   
    5. function ChildCircle(radius){    
    6.     this.base=Circle;   
    7.     this.base(radius);   
    8. }   
    9.   
    10. ChildCircle.prototype=new Circle(0);   
    11. function Circle_max(a,b){   
    12.     if (a.r > b.r) return a;   
    13.     else return b;   
    14. }   
    15.   
    16. ChildCircle.max = Circle_max;   
    17.   
    18. //使用ChildCircle子类   
    19. var c = new ChildCircle(1);   
    20. var d = new ChildCircle(2);    
    21. var bigger = d.max(c,d);    
    22. alert(bigger.area());  

    3.var式定义

    JS还支持一种var Circle={raidus:1.0,PI:3.1415}的形式,语法就如CSS的定义。
    因此如果Circle只有一个实例,下面的定义方式更简洁:

    1. var newCircle=   
    2. {   
    3.     r:1.0,   
    4.     PI:3.1415,   
    5.     area: function(){   
    6.         return this.PI * this.r * this.r;   
    7.     }   
    8. };   
    9.   
    10. alert(newCircle.area());  

    可以看看Rails带的OO Javascript库--Prototype
    其实,Javascript现在的语法真的不适合那么别扭的写成OO模式....
  • 相关阅读:
    第二十三讲:访问者模式
    第二十二讲:备忘录模式
    第二十讲:迭代模式
    第十九讲:职责链模式
    第十八讲:中介者模式
    UTC时间、GMT时间、本地时间、Unix时间戳
    【基础】SQL Server系统库的作用
    【基础】SQL Server系统库的作用
    【基础】SQL Server系统库的作用
    【收集】C#一些基础的面试题
  • 原文地址:https://www.cnblogs.com/zhuawang/p/1272619.html
Copyright © 2011-2022 走看看