[英]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. 是的,我知道我使用的术语根本不适用,也不适用于OOP语言。
When I define extension method in C# I can call it as instance method foo.call(bar)
or Foo.call(foo,bar)
. 当我在C#中定义扩展方法时,可以将其称为实例方法
foo.call(bar)
或Foo.call(foo,bar)
。 I defined a "extension" method for Array
equals(secondArray,comparer)
that checks the equality of the elements. 我为
Array
equals(secondArray,comparer)
定义了一个“扩展”方法,该方法检查元素的相等性。 I call it now as myArray1.equals(myArray2)
. 我现在将其称为
myArray1.equals(myArray2)
。
However I would like to call it also as Array.equals(myArray1,myArray2)
. 但是我也想称其为
Array.equals(myArray1,myArray2)
。
How to make it is possible JS-way? 如何使可能的JS方式?
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. 为了详细说明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));
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): 与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: this is the kind of code that is generated by Typescript when you write static methods. PS:这是Typescript在编写静态方法时生成的代码。 If you want to write JS is a OOP fashion, you may want to have a look at typescript: http://www.typescriptlang.org/
如果要编写JS是一种OOP方式,则可能需要看一下打字稿: http ://www.typescriptlang.org/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.