简体   繁体   中英

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

Yes, I know I used terms that do not apply at all or the way they apply to OOP languages.

When I define extension method in C# I can call it as instance method foo.call(bar) or Foo.call(foo,bar) . I defined a "extension" method for Array equals(secondArray,comparer) that checks the equality of the elements. I call it now as myArray1.equals(myArray2) .

However I would like to call it also as Array.equals(myArray1,myArray2) .

How to make it is possible JS-way?

You need to make two separate methods; one on the prototype and one one the function.

One of them can simply call the other one.

To elaborate on SLaks answer with an example: You can provide a "static" method and then provide an instance method that explicitly passes the instance to the static method.

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));

Console output:

true
true

Similarly to OozeMaster's answer, you can also write it in a more "OO" fashion this way (but still, you have to explicitly declare the "static" and member methods):

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: this is the kind of code that is generated by Typescript when you write static methods. If you want to write JS is a OOP fashion, you may want to have a look at typescript: http://www.typescriptlang.org/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM