添加自定义对象功能

时间:2012-07-13 06:30:50

标签: object javascript

我正在创建一个迷你JavaScript库,我试图让人们添加自定义函数。

目前的语法是:

$$.custom('alert', function(){alert(this._string)}); 

要触发警报,您​​将使用以下内容:

$$.string("Hi").alert();

问题是this._string应该在()之间返回字符串(它适用于正常函数),而是返回undefined

这是我用于设置$$对象的代码:

var g = function (a) {
        this._string = typeof a == "string" ? a : "undefined"
    },
    NumberPro = function (a) { 
        this._number = typeof a == "number" ? a : "undefined"
    },
    $$ = { 
        string: function (a) {
            return new g(a)
        },
        number: function (a) {
            return new NumberPro(a)
        },
        syntax: { 
            off: function () {
                for (var j in k) {
                    String.prototype[j] = String.prototype[j] || k[j];
                };
                for (var j in l) {
                    Number.prototype[j] = Number.prototype[j] || l[j];
                };
                type = 'prototype';
            },
            on: function () { 
                for (var j in l) {
                    NumberPro.prototype[j] = NumberPro.prototype[j] || l[j]
                }
                for (var j in k) {
                    g.prototype[j] = g.prototype[j] || k[j]
                }
                type = '';
            }
        },
        usePrototype: function (a) { 
            $$.syntax.off();
            a();
            $$.syntax.on();
        },
        custom: function(name, f){
            k[name] = f();
            for (var j in k) {
                    g.prototype[j] = g.prototype[j] || k[j]
                }
                type = '';
        }
    },
    type = '',
    Methods = $$;

k[name] = f()中的“custom”,function ...中,k是存储其余函数的对象。我运行for循环给出每个都是$$.string对象。

我想要做的是能够将this._string添加到自定义提醒功能中提交的功能中。我认为这可能是可能的,但我似乎无法让这个工作。我希望我提供足够的代码,这样我就可以得到一个好的答案。我虽然我的方式应该工作,因为在自定义函数中我再次运行for来为$$对象提供添加的函数,所以this._string应该检索字符串。

提前致谢。

0 个答案:

没有答案