何时有时将对象类型定义为将实例绑定方法镜像为构造函数上的静态实用程序函数很有用

When is it sometimes useful to defining object types to mirror instance-bound methods as static utility functions on the constructor?

本文关键字:构造函数 静态 实用程序 有用 函数 镜像 绑定 对象 类型 定义 何时      更新时间:2023-09-26

我是JavaScript的初学者,目前正在阅读Thomas A. Powell,Fritz Schneider的完整参考第3版

我正在学习类属性的路上。

我引用同一本书的摘录。
当定义对象类型将实例绑定方法镜像构造函数上的静态实用程序函数时,它有时也很有用。例如,String.prototype.trim()字符串实例方法,它对调用它的实例进行操作。但是,可以定义一个静态实用程序函数,例如 String.trim(),它将它应该操作的字符串实例作为其唯一参数:

if(typeof String.trim == "undefined"){
                String.trim = function(str){
                    alert("Here!");
                    return str.trim();
                }
}
var test = "             The International Jew          ";
alert(test.trim());                                        // The International Jew 
alert(String.trim("          The International Jew"));     // The International Jew

发现自己对上述功能给我什么用途感到非常困惑,什么会真正促使我从某个实例方法静态实用程序函数进行这种转换?
亲切地指导我理解这个概念,因为我是编程世界的新手。

我使用静态方法而不是实例方法的一个原因是处理空/未定义的对象。如果使用实例方法,则始终必须在所有位置包装修剪调用

if (typeof str == "string") {
    str = str.strim();
} else {
    str = ""; // If you want this
}

然而,如果你有一个静态方法,调用方可以安全地给它一个空/未定义的对象。

String.trim = function(str){        
    return typeof str == 'string' ? str.trim() : '';
}
var str;
// String.trim can handle the undefined object
str = String.trim(str);

此外,正如 dandavis 所提到的,您可以将该String.trim作为回调传递给 forEachmap 等函数,而无需指定this是什么。

var trimmed = [" a ", " b ", "c "].map(String.trim);

但是,请注意,这才有可能,因为我们的静态String.trim不使用 this ,但您可能会发现有些使用静态方法中的this来引用构造函数,在这种情况下,您需要绑定它。

例如:

String.doubleTrim = function(str) {
    var trimmed = this.trim();
    return trimmed + trimmmed;
} 
// Error trim is not a function
var doubleTrimmed = [" a ", " b ", "c "].map(String.doubleTrim);
// This is OK
var doubleTrimmed = [" a ", " b ", "c "].map(String.doubleTrim.bind(String));
Note that you could work around the above problem by calling `String.trim()` instead of `this.trim()` but some prefer that because it lets you rename your object from a single place.

这是一个很好的问题。我认为如果你是初学者,最好推迟这部分并继续学习 JavaScript 的其他部分。但是我要回答你。当我们想要使用或更改对象的基本特征时,我们使用原型(或您所说的"实例方法")。当我们想要利用类型或类中函数的能力时,我们也使用静态实用程序函数

例如

当你想把字符串类型的"修剪"**能力提供给另一个类(例如继承),你可以使用原型。此外,当您想要更改类或方法的内置功能时,可以通过更改 **Prototype 来更改它。您可以使用原型编辑,继承和利用类型或类的整个特征。还可以向内置类添加新功能(方法)。

使用 Prototype,您可以通过其对象层次结构操作整个 JavaScript 功能。这就是为什么JavaScript是惊人的。

但是,当您想要使用函数、类型或类的功能时,请使用静态实用程序函数。

在下面的链接中,我谈到了JavaScript具有的一些奇妙功能。然而,这篇文章是关于更大的东西,但在第一节中,我已经谈到了一些鼓舞人心的 JavaScript 能力。

http://www.codeproject.com/Articles/844789/A-Belly-Dance-in-Holy-Lands-of-MVC-MVP-and-MVVM-Pa#xx4977789xx