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

本文介绍了四种不同的方式来实现动画的启动和停止,包括过程式程序设计、对象形式、使用Function对象扩展方法以及支持链式调用的方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

方法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(){
//...
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值