【问题标题】:how to define a custom method on the javascript object class如何在 javascript 对象类上定义自定义方法
【发布时间】:2014-04-07 09:42:40
【问题描述】:

我在查看Javascript the good parts 时遇到了这个例子,作者试图解释如何能够调用超类:

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

使用此代码的示例:

super_get_name = that.superior('get_name');

但是 chrome 无法识别 Object 上的 method。我尝试使用defineProperty 做同样的事情,但这也没有用.. 有什么帮助吗?

更新: 此方法是否会导致与 jQuery 的任何已知冲突?只要我将以下内容放在页面中的第一个 js 文件中:

我在 jquery-1.11.0.js 的第 2062 行收到此错误:

Uncaught TypeError: Object function (name) {
    var that = this,
        method = that[name];
    return function (  ) {
        return method.apply(that, arguments);
    };
} has no method 'exec' 

这是受影响的代码:

    // Filters
    for ( type in Expr.filter ) {
        if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
            (match = preFilters[ type ]( match ))) ) {
            matched = match.shift();
            tokens.push({
                value: matched,
                type: type,
                matches: match
            });
            soFar = soFar.slice( matched.length );
        }
    }

知道发生了什么吗?

【问题讨论】:

  • 在那本书的某处他确实定义了一个自定义method 函数。使用它!
  • @Bergi 似乎使用它会弄乱我的 jquery .. 有没有办法避免它?

标签: javascript oop design-patterns


【解决方案1】:

这本书的作者解释说,要让那段代码工作,你需要先定义方法函数:

Throughout the book, a method method is used to define new methods. This is its definition:

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

【讨论】:

  • 所以这意味着一个人实际上不应该在Objectavoid messing up the Object.prototype上使用method
  • @Bergi:你的问题不清楚。 Object 默认没有方法 method。所以要使用它,你必须“弄乱”原型。正如另一个问题所说:您需要意识到人们正在更改原型,因此请使用正确的循环结构。
  • method 是一个Function 方法,这意味着它不会搞砸Object.prototype。仅将其应用于Object 将...正如我对另一个问题的回答所说,更改循环构造不是解决方案。
【解决方案2】:

似乎使用它会弄乱我的 jquery.. 有没有办法避免它?

是的。将Function.prototype.method重新定义为

Function.prototype.method = function (name, func) {
  Object.defineProperty(this.prototype, name, {
    configurable: true,
    enumerable: false, // sic!
    writable: true,
    value: func
  });
  return this;
};

Object 函数上使用它之前(Function.prototype.method 本身不会弄乱 jQuery,但调用 Object.method() 会)。另见How to define method in javascript on Array.prototype and Object.prototype so that it doesn't appear in for in loop

【讨论】:

  • 看起来你在 SO 上没有 80K+ 的分数!无论如何,你能推荐我一个关于如何在 javascript 中调用超类的 good 教程吗?它是一种非常灵活的语言,似乎每个人和他们的嫂子对如何做任何事情都有自己的看法。我想要一些清晰且经过时间考验的东西。 javascript the good parts 中的示例非常初级和基础,并没有完全解决我的情况。
  • 我倾向于明确地call 它,因为laid out here :-) 100% 有效,灵活,但有点冗长,可以使用一些缓存优化。
猜你喜欢
  • 1970-01-01
  • 2019-11-08
  • 2010-10-05
  • 2019-04-15
  • 2020-09-07
  • 2015-06-17
  • 1970-01-01
  • 2013-04-08
  • 1970-01-01
相关资源
最近更新 更多