Javascript 为什么字符串类会从Function.prototype扩展?

Javascript 为什么字符串类会从Function.prototype扩展?,javascript,Javascript,我正在阅读《JavaScript好的部分》一书,看到了以下代码: Function.prototype.method = function (name, func) { this.prototype[name] = func; return this; }; String.method('trim', function ( ) { return this.replace(/^\s+|\s+$/g, ''); }); document.writeln('"' + " neat ".trim

我正在阅读《JavaScript好的部分》一书,看到了以下代码:

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

String.method('trim', function ( ) {
 return this.replace(/^\s+|\s+$/g, '');
});
document.writeln('"' + " neat ".trim( ) + '"');

使我困惑的是,在
Function.prototype.method
定义中,它只是扩展了Function类的
prototype
属性,并且应该与
Object.prototype
无关。那么,为什么在这种情况下
String
对象仍然具有
方法
方法呢

因为构造函数是函数,所以
String
是一个带有
原型的函数。
Function.prototype.method
允许您在任何函数的原型中添加一个方法,在本例中为
String
要回答这个问题,让我们首先看看
String
是什么:

> typeof String
"function"
它是一个函数,所以在
函数.prototype上定义的任何东西都是“继承的”;让我们看看
method()
的作用:

this.prototype[name] = func;
这里,
this.prototype
指的是
String.prototype
,因此,这段代码实际上是:

String.prototype.trim = function() { ... }

您是从String()调用它的,所以String==this…That
Function.prototype.method
是一个相当愚蠢的速记方法。@MattBall:尤其是在初学者的书中…@MattBall为什么这么愚蠢?它完全没有必要。它并没有使您的代码更简洁,只是不那么清晰。为什么我们不能简单地使用
this[name]=func
,而必须使用
this.prototype[name]=func
?@OneZero:第一个定义静态方法,第二个定义继承的方法。你说的“自动装箱”是什么意思?目前看来,这听起来是错误的。字符串文本不会传递给
String
函数。@Bergi它实际上对答案没有帮助,所以我已经去掉了它。