如何定义扩展方法并将其作为实例和静态方法调用

How to define extension method and call it as instance and static method?

本文关键字:实例 调用 静态方法 何定义 定义 方法 扩展      更新时间:2023-09-26

是的,我知道我使用的术语根本不适用,或者它们适用于OOP语言的方式。

当我在 C# 中定义扩展方法时,我可以将其调用为实例方法 foo.call(bar)Foo.call(foo,bar) 。我为Array equals(secondArray,comparer)定义了一个"扩展"方法,用于检查元素的相等性。我现在称之为myArray1.equals(myArray2).

但是,我也想称它为Array.equals(myArray1,myArray2)

如何使JS-way成为可能?

用一个例子来详细说明 SLaks 的答案:您可以提供一个"静态"方法,然后提供一个实例方法,将实例显式传递给静态方法。

var Obj = function(){
    var _this = this;
    this.x = 5;
    this.equals = function(other){
        return Obj.equals(_this, other);
    }
}
Obj.equals = function(obj1, obj2){
    return obj1.x == obj2.x;
}
obj1 = new Obj();
obj2 = new Obj();
console.log(obj1.equals(obj2));
console.log(Obj.equals(obj1, obj2));

控制台输出:

true
true

你需要创建两个单独的方法;一个在原型上,一个在函数上。

其中一个可以简单地调用另一个。

与 OozeMaster 的答案类似,您也可以以更"OO"的方式编写它(但仍然必须显式声明"静态"和成员方法):

var Operation = (function () {
    function Operation(firstOperand) {
        this.firstOperand = firstOperand;
    }
    Operation.prototype.add = function (other) {
        console.log(this.firstOperand + other);
    };
    Operation.add = function (first, second) {
        console.log(first + second);
    };
    return Operation;
})();

Operation.add(1, 2); // prints 3
var op = new Operation(3);
op.add(4); // prints 7

PS:这是Typescript在编写静态方法时生成的那种代码。如果你想写JS是一种OOP时尚,你可能想看看打字稿:http://www.typescriptlang.org/