• 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(){
            ....
        });


  • 相关阅读:
    开源项目:MMTweenAnimation
    URI跳转方式地图导航的代码实践
    处理i18n国际电话区号的代码实践
    图片变形的抗锯齿处理方法
    CocoaPods版本升级
    JSPatch 部署安全策略
    JSPatch实现原理详解<二>
    JSPatch实现原理详解
    JSPatch – 动态更新iOS APP
    iOS富文本组件的实现—DTCoreText源码解析 渲染篇
  • 原文地址:https://www.cnblogs.com/hustskyking/p/3049803.html
Copyright © 2020-2023  润新知