【问题标题】:javascript prototype not workingjavascript原型不工作
【发布时间】:2012-02-18 06:19:08
【问题描述】:

我误会了 .prototype 应该做什么,还是这不起作用??

window.dump = function () {
    for (var i = 0, x = dump.list.length; i < x; ++i) console.log.apply(this, dump.list[i]);
    if (arguments.length && typeof arguments[0] === 'boolean' && arguments[0]) dump.purge();
}
dump.prototype = {
    list : [],
    log : function () {
        dump.list.push(arguments);
    },
    purge : function () {
        dump.list = [];
    }
}
dump.log('test1');
dump.log('test2');
dump();

我希望“test1”和“test2”通过console.log,而不是dump.log 没有定义。但是dump.prototype.log 是。

编辑:我尝试了以下方法,但我似乎无法正确处理这个原型。

window.dump = new function () {
    this.list = [];
    this.log = function () {
        this.list.push(arguments);
    }
    this.purge = function () {
        return this.list = [];
    }
    return function () {
        for (var i = 0, x = this.list.length; i < x; ++i) console.log.apply(this, this.list[i]);
        if (arguments.length && typeof arguments[0] === 'boolean' && arguments[0]) this.purge();
    }
}

我想我要问的是,能够如下使用我的代码的正确方法是什么?

dump.log('test1');
dump.log('test2');
dump();

编辑:感谢 Matthew Flaschen 为任何有兴趣从中构建的人提供最终结果。

(function () {
    var console_log = Function.prototype.bind.call(console.log, console);
    window.dump = function () {
        for (var i = 0, x = dump.list.length; i < x; ++i) console_log.apply(this, dump.list[i]);
        if (arguments.length && typeof arguments[0] === 'boolean' && arguments[0]) dump.purge();
    };
    dump.list = [];
    dump.log = function () {
        dump.list.push(arguments);
    }
    dump.purge = function () {
        dump.list = [];
    }
})();

我不得不指定console_log 来包装console.log,因为显然console 不是标准对象。因此,它不是带有apply 方法的标准Function 对象。证明我确实使用过 Google。

【问题讨论】:

    标签: prototype javascript function-prototypes


    【解决方案1】:

    是的,正确的版本如下。 dumper 是一个构造函数。因此,它初始化了list 成员。

    下面,我们使用所需的方法设置dumper 原型。这些也可以使用thisdumper 的任何实例(例如d)都会有这些方法。

    window.dumper = function () {
        this.list = [];
    };
    
    dumper.prototype = {
    
        log : function () {
            this.list.push(arguments);
        },
        purge : function () {
            this.list = [];
        },
        dump : function () {
            for (var i = 0, x = this.list.length; i < x; ++i) console.log.apply(this, this.list[i]);
            if (arguments.length && typeof arguments[0] === 'boolean' && arguments[0]) this.purge();
        }
    }
    
    
    var d = new dumper();        
    
    d.log('test1');
    d.log('test2');
    d.dump();
    

    【讨论】:

    • 有没有办法真正使用“d”作为转储函数?
    • @andrewjackson,如果你把dump 设为单身的话。但这违背了使用prototype 的全部意义。除非迫不得已,否则不要试图与 JavaScript 对象模型作斗争。
    • 我不想成为一个痛苦的人,但是你有一个单身人士的例子,这会让这成为可能吗?仅供参考...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    相关资源
    最近更新 更多