On Jun 17, 2015, at 8:09 AM, Andrea Giammarchi wrote:

> Mostly every Array extra in ES5 would work with those functions, e.g.
> 
> ```js
> function multiplyPoints (_p2) {
>   var { x1: x, y1: y } = this;
>   var { x2: x, y2: y } = _p2;
>   return { x: x1 * x2, y: y1 * y2 };
> }
> 
> var multiplied = manyPoints.map(multiplyPoints, centralPoint);
> ```
> 
> It's not that common pattern but it gives you the ability to recycle 
> functions as both methods or filters or mappers or forEachers and vice-versa.
> 
> I personally use those kind of functions quite a lot to be honest, most 
> developers keep ignoring Array extra second parameter as context though, they 
> probably use a wrapped fat arrow within an IFI with call(context) :D
> 

It seems to me that  we already can quite nicely express in ES6 the use of a 
function as a method:

```js
function multiplyPoints({x1, y1}, {x2,y2}) {
    return { x: x1 * x2, y: y1 * y2 }
}

class Point {
   multiply(p2) {return multiplyPoints(this, p2)}
}
```

or, perhaps a bit more OO

```js
class Point {
   static multiply({x1, y1}, {x2,y2}) {
      return new Point(x1 * x2, y1 * y2 )  //or new this(...) if you care about 
subclassing Point
   }

   multiply(p2) {return Point.multiply(this, p2)}

   constructor(x,y) {
      this.x = x;
      this.x = y;
   }
}
```

Regardless of how you express it, if you want the same function to be used both 
as a standalone function and as an method, you are going to have to have a line 
or two of code to install the function as a method.  To me, the one-line method 
definitions used above are about as concise and much clearer in intent than 
`Point.prototype.multiply=multiplyPoints;` or whatever other expression you 
would use to install such a function as a method.  And I would expect any high 
perf JIT to use inlining to completely eliminate the indirection so, where it 
matters, there probably wound't be any performance difference.

Many JS programmers have historically been confused about the JS semantics of 
`this` because it is over-exposed in non-method functions. Things like the 
current proposal increases rather than mitigates the potential for such 
confusion. if you are programming in a functional style, don't write functions 
that use `this`.  If you need to transition from to/from OO and functional 
styles, be explicit as shown above.

`this` is an OO concept.  FP people, `this` is not for you;  don't use it, 
don't try to "fix it". 

Allen


_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to