HomeGithub个人博客Weibo订阅

javascript的灵活性

  Barret李靖  阅读(617)  评论(0编辑  收藏  举报

 本文从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(){
        ....
    });
复制代码

 


编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示