否”;函数.方法”;在JavaScript中

No "Function.method" in JavaScript?

本文关键字:JavaScript 函数 方法      更新时间:2023-09-26

我正在读Douglas Crockford的书,他使用了的结构

Function.method('inherits', function(Parent){
   this.prototype=new Parent();
   return this;
});

如果我们不考虑它的含义,我根本无法绕过语法。我试着在chrome中运行它,并获得

Uncaught TypeError: undefined is not a function test3.html:18
(anonymous function)

如果我尝试(jsfiddle)也会发生这种情况

Function.method("test", function () { return "TEST"; });

似乎有一个帖子说这条线有效,但我无法让它发挥作用。为什么会这样?

在您引用的帖子中,该行之所以有效,是因为Function.prototype已使用以下方法进行了扩展:

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

如果你运行上面的代码,然后才运行你所拥有的代码,一切都会正常工作——或者你可以把.method改为.prototype[name_here] =,一切都一样。

关于最佳做法的说明

如果你要在这个时代扩展原型,最好使用Object.defineProperty来确保该方法是不可枚举的。