簡體   English   中英

如何定義擴展方法並將其稱為實例和靜態方法?

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

是的,我知道我使用的術語根本不適用,也不適用於OOP語言。

當我在C#中定義擴展方法時,可以將其稱為實例方法foo.call(bar)Foo.call(foo,bar) 我為Array equals(secondArray,comparer)定義了一個“擴展”方法,該方法檢查元素的相等性。 我現在將其稱為myArray1.equals(myArray2)

但是我也想稱其為Array.equals(myArray1,myArray2)

如何使可能的JS方式?

您需要制作兩種單獨的方法; 一在原型上,一在功能上。

其中一個可以簡單地呼叫另一個。

為了詳細說明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”的方式編寫它(但仍然必須顯式聲明“ static”和成員方法):

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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM