tc39 / proposal-bind-operator

This-Binding Syntax for ECMAScript
1.75k stars 30 forks source link

An idea about limiting the function which can be called by this operator #59

Closed Frimaire closed 1 year ago

Frimaire commented 1 year ago

Hi,

It would be better if the function which can be call by this operator is required to be declared in a specified way.

Example:

var {::forEach, ::every, ::some, ::map, ::reduce} = Iterator.prototype;
// or ::forEach = Iterator.prototype.forEach;

function ::addClass(name) {
    this::forEach(e => e.classList.add(name));
}

range(1, 100)::reduce((s, x) => s + x, 0);     // 4950
[...range(0, 360)::map(x => Math.cos(x / 180 * Math.PI))];     // [1, 0.99984, 0.99939, ......]    
document.querySelectorAll("p")::addClass("hidden");

Also, @ operator from deprecated E4X, may be a alternative choice:

var  @forEach = Iterator.prototype.forEach;
function @addClass(name) {
    this.@forEach(e => e.classList.add(name));
}
bathos commented 1 year ago

It would be better [...]

Why? This would prevent the proposal from addressing key use cases entirely and it’s unclear to me what advantage it would be providing for others.

Frimaire commented 1 year ago

prevent scope pollution because the variable can no longer be called in the ordinary style(this === undefined)

for instance, in jQuery, the functions which need this binding are majorly Object.prototype.hasOwnProperty, Array.prototype.slice and Array.prototype.push

Well, I agree that the advantage is negligible.

ljharb commented 1 year ago

Object.hasOwn exists now for the first one, and push is generally avoided as a form of mutation, and there’s a proposal already for slice syntax.