Scoped binding of a method to an object

Rick Waldron waldron.rick at gmail.com
Sun Oct 13 09:05:54 PDT 2013


On Sun, Oct 13, 2013 at 3:54 AM, Benjamin (Inglor) Gruenbaum <
inglor at gmail.com> wrote:

> Scoped binding of a method to an object
>
> Well, I know how some languages solve this issue but I wondered if
> ECMAScript considered addressing this or already have and I missed it.
>
> Often, I want to extend objects, for example -
>
> Array.prototype.shuffle - takes an array and shuffles it.
>
> However, this is considered bad practice for many reasons I don't have to
> repeat here (what if other libraries also override it? What if some user
> code? What if it makes it to the standard some day?)
>
> The problem is even more prevalent in stuff like String.prototype.contains
> which we know will be in the next spec - people had little way to add that
> function to the string prototype *before* it was adapted to the spec and
> not get eventually bitten.
>
> Stuff like underscore _.shuffle makes for less object oriented code, I
> find it harder to write and it feels like the code is not where it belongs.
>
> What I'd like is a way to add such methods in a scoped way, so within *my* code
> I get to use .shuffle but any code that is not in that scoped block does
> not get access to this method.
>
> Has there been a proposal or discussion about this in the past?
>

This is trivial with Symbols:

  let shuffle = Symbol();

  Array.prototype[shuffle] = function() {...};


Only code that has access to the `shuffle` symbol may use the method:

  let shuffled = array[shuffle]();


Rick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20131013/1bb083a9/attachment.html>


More information about the es-discuss mailing list