javascript实现同一任务的6种方式

需求:启动和停止一个动画

方法1:过程式的程序设计

/* Start and stop animations using functions */
function startAnimation(){
        //...
} 
function stopAnimation(){
        //...
}

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

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

/* USage */
var myAnim = new Anim():
myAnim.start();
myAnim.stop();

上述代码定义了一个名为Anim的类,并把两个方法赋给该类的prototype属性。
如果你更喜喜欢把类的定义封装在一条声明中,则可改用下面的代码:

方法3:

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

这在传统的面向对象程序员看来可能更眼熟一点,他们习惯于看到类的方法声明内嵌在类的声明之中。如果你以前用过这样的编程风格,可能想尝试一下下面的示例:

方法4:

/* Add a method to the Function object that can used to declare methods. */
Function.prototype.method = function(name,fn){
    this.prototype[name] = fn;
};

/* Anim class,with methods created using a convenience method. */
var Anim = function(){
        //...
};
Anim.method('start',function(){
        //...
});
Anim.method('stop',function(){
        //...
});

Function.prototype.method用于为类添加新方法。它有两个参数。第一个是字符串,表示新方法的名称;第二个是用作新方法的函数。

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

/* THis version allows 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 method and chaining. */
var Anim = function(){//...};
Anim.method('start',function(){
//...
})
.method('stop',function(){
//...
});

猜你喜欢

转载自blog.csdn.net/zjsfdx/article/details/80418257