javascript面向对象编程(一)

 

javascript曾一度被认为是玩具型的语言,因为它太容易上手,而且,javascript曾一度担任为web站点“打杂”的职责。直到Ajax的兴起,这个在幕后默默无闻多年的语言才崭露头角,它的灵活性赋予了开发者无穷的想象力。javascript不提供传统的OOP方式,但是仍然可以轻松的实现OOP。

[强大的原型prototype]
这是一段来自《javascript design patterns》的代码:

JavaScript:
  1. /* Start and stop animations using functions. */
  2.  
  3. function startAnimation ( ) {
  4.   ...
  5. }
  6.  
  7. function stopAnimation ( ) {
  8.   ...
  9. }
  10.  
  11.  
  12.  
  13. /* Anim class. */
  14.  
  15. var Anim = function ( ) {
  16.   ...
  17. };
  18. Anim. prototype. start = function ( ) {
  19.   ...
  20. };
  21. Anim. prototype. stop = function ( ) {
  22.   ...
  23. };
  24.  
  25. /* Usage. */
  26.  
  27. var myAnim = new Anim ( );
  28. myAnim. start ( );
  29. ...
  30. myAnim. stop ( );
  31.  
  32.  
  33.  
  34. /* Anim class, with a slightly different syntax for declaring methods. */
  35.  
  36. var Anim = function ( ) {
  37.   ...
  38. };
  39. Anim. prototype = {
  40.   start: function ( ) {
  41.     ...
  42.   },
  43.   stop: function ( ) {
  44.     ...
  45.   }
  46. };
  47.  
  48.  
  49.  
  50. /* Add a method to the Function class that can be used to declare methods. */
  51.  
  52. Function. prototype. method = function ( name, fn ) {
  53.   this. prototype [ name ] = fn;
  54. };
  55.  
  56. /* Anim class, with methods created using a convenience method. */
  57.  
  58. var Anim = function ( ) {
  59.   ...
  60. };
  61. Anim. method ( 'start', function ( ) {
  62.   ...
  63. } );
  64. Anim. method ( 'stop', function ( ) {
  65.   ...
  66. } );
  67.  
  68.  
  69.  
  70. /* This version allows the calls to be chained. */
  71.  
  72. Function. prototype. method = function ( name, fn ) {
  73.     this. prototype [ name ] = fn;
  74.     return this;
  75. };
  76.  
  77. /* Anim class, with methods created using a convenience method and chaining. */
  78.  
  79. var Anim = function ( ) {
  80.   ...
  81. };
  82. Anim.
  83.   method ( 'start', function ( ) {
  84.     ...
  85.   } ).
  86.   method ( 'stop', function ( ) {
  87.     ...
  88.   } );

这段代码充分展示了javascript的OO能力,相信你也早就见识过,毕竟这已经不是新闻了。见过的一篇比较好的关于prototype原型的文章:不是原型继承那么简单!!prototype的深度探索,推荐大家看看。

转:http://canque.rssidea.com/javascript_oop_part1/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值