zoukankan      html  css  js  c++  java
  • javascript的灵活性

     本文从ITeye导入

     

    如果你偏爱过程式编程,你可以这样:

    /*Start and stop animations using functions.*/
    function startAnination() {
        ....
    }
    function stopAnination(){
        ....
    }

    这种做法很简单,但是你无法创建可以保存状态并且具有一些仅对其内部状态进行操作的方法的动画对象。

    下面的代码定义了一个类,你可以用它创建这种对象:

    /*Anim class.*/
     var Anim = function(){
        ....
     };
     Anim.prototype.start = function(){
        ....
     };
     Anim.prototype.stop = function(){
        ....
     };
    
     /*Usage.*/
     var myAnim = new Anim();
     myAnim.start();
     ....
     myAnim.stop();

    上述代码定义了一个名为Anim的类,并把两个方法赋给该类的prototype的属性。

    如果你更喜欢把类的定义封装在一条声明中,则可以改用下面的代码:

    /*Anim class, with a slightly different syntax for declaring methods*/
    var Anim = function(){
        ....
     };
     Anim.prototype = {
        start : function(){
            ....
        };
        stop : function(){
            ....
        };
    };

    这在传统的面向对象程序员看来肯呢过更眼熟一点,他们习惯于看到类的方法声明内嵌在类的

    声明之中。要是你以前用过这样的编程风格,可能想尝试下下面的是里。

    /*Add method to the Function object that can be used to declare methods*/
    Function.prototype.methed = function(name, fn){
        this.prototype[name] = fn;
    };
    
    /*Anim class, with ,methods created using a conbenience ,method.*/
    var Anim = function(){
        ....
    };
    Anim.method('start', function(){
        .....
    });
    Anim.method('stop', function(){
        ....
    });

    Function.protytype.method用于为类添加新方法。他有两个参数,第一个是字符串,表示新方法

    的名称;第二个是用作新方法的函数。

    你可以进一步修改Function.prototype.method, 使其可被链式调用。这只需要在他返回this

    值即可:

    /*This version alllows the calls to be chained.*/
    Function.prototype.method = function(name, fn){
        this.prototype[name] = fn;
        return this;
    };
    
    /*Anim class, with methods created using a convenience and chaining.*/
    var Anim = function(){
        ....
    };
    Anim.
        method('start', function(){
            ....
        }).
        method('stop', function(){
            ....
        });


  • 相关阅读:
    Scala 中 for 循环 和 generator 的使用例子
    [转] tomcat进程意外退出的问题分析
    [转] Android:用GSON 五招之内搞定任何JSON数组
    [转] Scala 2.10.0 新特性之字符串插值
    [转] JQuery UI Tabs 动态添加页签,并跳转到新页签
    vim常用快捷键
    [转] 利用dockerize模板为容器内应用生成配置文件和环境变量
    [转] linux权限补充:rwt rwT rws rwS 特殊权限
    [转] #!/bin/sh & #!/bin/bash区别
    [转] 利用shell创建文本菜单与窗口部件的方法
  • 原文地址:https://www.cnblogs.com/hustskyking/p/3049803.html
Copyright © 2011-2022 走看看