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


  • 相关阅读:
    第6天c#基础结构体和数组
    第5天c#基础for循环和enum
    第4天c#基础switch和while循环
    第3天c#按位运算和增减buff
    第2天c#基础
    第1天c#基础语法
    背景图层填充底色调密度
    如何在运行里添加命令
    网站
    BAT设置
  • 原文地址:https://www.cnblogs.com/hustskyking/p/3049803.html
Copyright © 2011-2022 走看看