【问题标题】:TypeError: Object function Object() { [native code] } has no method 'method'TypeError: Object function Object() { [native code] } has no method 'method'
【发布时间】:2013-11-20 02:28:32
【问题描述】:

浏览 Javascript: The Good Parts 5.4 章的示例代码,以下用于演示使用函数式模式调用超级方法:

Object.method('superior', function (name) {
    var that = this, method = that[name];
    return function () {
        return method.apply(that, arguments);
    };
});

这将按如下方式使用(其中“cat”是另一个定义了“get_name”函数的构造函数):

var coolcat = function (spec) {
    var that = cat(spec),
        super_get_name = that.superior('get_name');
    that.get_name = function (n) {
        return 'like ' + super_get_name(  ) + ' baby';
    };
    return that;
};

但是在运行示例代码时,F12 工具显示如下:

Uncaught TypeError: Object function Object() { [native code] } has no method 'method'.

我在这里错过了什么?

【问题讨论】:

标签: javascript


【解决方案1】:

Douglas Crockford 使用以下内容(在本书第 4 页定义)

Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
};

【讨论】:

  • 就是这样。谢谢。
【解决方案2】:

那是因为你的代码中没有定义方法method,查书找作者定义方法method的地方。

显然@Andreas 找到了方法,现在我记得了。

使用method 方法,以便当在任何对象上调用它时,它会在该对象上定义一个方法,其中该方法的名称是传递给methodname 参数,以及该方法的实现方法是func函数参数。

您需要将其包含在控制台中才能正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多