• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Joanna Qian
Stay Hungry, Stay Foolish!
博客园    首页    新随笔    联系   管理    订阅  订阅
JavaScript 多种方法实现类(转)

摘自:http://www.nowamagic.net/javascript/js_MethodsToCreateClass.php

构造方法

function coder()
{
    this.name = '现代魔法';
    this.job = 'Web 开发者';
    this.coding = function ()
    { alert('我正在写代码'); }
}

var coder = new coder();
alert(coder.name);
coder.coding();

工厂方法

function createCoderFactory()
{
    var obj = new Object();
    obj.name = '现代魔法';
    obj.job = '程序员';
    obj.coding = function ()
    {
        alert('我正在写代码');
    };
    return obj;
}
var coder = createCoderFactory();
alert(coder.name);
coder.coding();

工厂方法和构造方法都有着一个相同的缺点,就是每创建一个实例,都会实例化该类的每个函数。

原型链

function coder(){}
coder.prototype.name = '现代魔法';
coder.prototype.job = '程序员';
coder.prototype.coding = function(){
    alert('我正在写代码');
};
var coder = new coder();
alert(coder.name);
coder.coding();

原型链有个缺点就是它所有属性都共享,只要一个实例改变其他的都会跟着改变。如:

var coder1 = new coder();
var coder2 = new coder();
alert(coder1.name);     /*显示现代魔法*/
coder2.name = 'nowamagic';
alert(coder1.name);     /*显示nowamagic*/
alert(coder2.name);     /*这个也显示nowamagic*/

混合方式

以上三种都有着各自的缺点,所以我们要加以改进。

function coder()
{
    this.name = '现代魔法';
    this.job = '程序员';
}
coder.prototype.coding = function(){
    alert('我正在写代码');
};

动态原链

要解决前三种的缺点,还有一种方法。

function coder()
{
    this.name = '现代魔法';
    this.job = '程序员';
    if (typeof(coder._init) == 'undefined')
    {
        this.coding = function ()
        {
            alert('我正在写代码');
        };
        this._init = true;
    }
}

 

 

posted on 2013-05-01 02:10  Joanna Qian  阅读(277)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3