Skip to content
This repository was archived by the owner on Apr 3, 2025. It is now read-only.
This repository was archived by the owner on Apr 3, 2025. It is now read-only.

Suggestion: operator() and operator new #52

Open

Description

@yw662

An operator() can make an object become a Callable with a function signature without actually make it a function.
And a similar operator new is also suggest to make the object a constructor.

like this:

const foo = {
  value: 1,
  bar: {
    value: 2,
    [Symbol.operatorSet]: Operators.create({
      "()"(thisArg, callee, ...args) {
        return thisArg.value + callee.value + args[0]
      },
      "new"(callee, ...args) {
        return Object.create(callee)
      }
    })
  }
}

foo.bar(3) // 6
new foo.bar() // { [[prototype]]: foo }

(It might be a bad idea to actually allow the same object to have different operator() and operator new, but, who knows.)

Activity

  1. ljharb commented on Dec 29, 2021

    @ljharb
    Member

    What would typeof foo.bar be? If it's not function, it must never be callable, since the spec says that those two things are always the same (and code relies on it)

  2. jhmaster2000 commented on Feb 7, 2022

    @jhmaster2000

    There's no reason or need for either of these in JS

    • operator new overloading is only ever used on other languages such as C++ for modifying memory management and manually implementing GC (in combination with operator delete overloading), both of which in JS either don't exist or are managed by the internal engine.
    • For the nominated use case of "making an object a constructor", that's literally just a regular class with a constructor and static properties.
    • Likewise, operator() is needed in other languages like C++ because there functions are not objects, unlike in JS, where a "callable object" and a Function are essentially the same thing to the extent of use cases overloading operator() on a plain object would have. If you want to have an object that is ONLY callable but not constructable, you can simply use new.target on your function.

    So to summarize, there would be nearly zero benefit in making those two operators overloadable in JS, quite the contrary, it would just hurt the ecosystem making function and class calls even more unpredictable than they already are with all the hacks described above, aswell as monkeypatching, prototype pollution, proxies, among others.

  3. C-Ezra-M commented on Dec 6, 2022

    @C-Ezra-M

    I don't even see a point in making the new operator required for classes. JavaScript does not have to deal with manual memory management, and even that operator is not in Python and Kotlin. (In Ruby and Rust, new is used as a suffix: Array.new in Ruby and Vector::new() in Rust).

    In Python, you can make an object callable because functions are objects.

    In short, () should be overloadable, while new should not be.

  4. Haringat commented on Jan 4, 2023

    @Haringat

    @jhmaster2000 I totally agree with your point on the new operator new however the invoke operator (while probably painful to implement) would IMO be a nice addition. Kotlin showed how that operator can open up new possibilities.

  5. jhmaster2000 commented on Mar 14, 2023

    @jhmaster2000

    @jhmaster2000 I totally agree with your point on the new operator new however the invoke operator (while probably painful to implement) would IMO be a nice addition. Kotlin showed how that operator can open up new possibilities.

    Could you show a JS example of one of those "new possibilities" overloading the () operator specifically would open that could not be done with some combination of Proxies, bound functions and new.target?

  6. Haringat commented on Jun 7, 2023

    @Haringat

    @jhmaster2000 Well, first of all: You cannot trap apply on objects using proxies. You would have to make every object, on which you might want to overload the () operator, a function, only to be able to trap apply. That would be possible, but it is a pain.

    As for new.target: I am highly against overloading new.

  7. FrameMuse commented on Jun 7, 2023

    @FrameMuse

    Is new operator? I always thought it's a keyword like yield or let.

  8. ljharb commented on Jun 7, 2023

    @ljharb
    Member

    yield and new are both operators.

  9. FrameMuse commented on Jun 7, 2023

    @FrameMuse

    According to MDN, it's a keyword and operator at the same time.

    The yield operator is used to pause and resume <...>

    The yield keyword pauses generator function execution <...>

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield#description


    The same with new

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new


    That's sad because I thought there is a line between operator and keyword.
    Then it doesn't give any hint to choose what operators should be overloadable.

  10. Haringat commented on Jun 7, 2023

    @Haringat

    @FrameMuse newis in JS - like in most other languages - an operator. In C++ it is even overloadable, but few other languages allow for that as it is only useful to change the memory allocation which is not an issue for languages like Java or JS so overloading it makes little sense.

  11. Haringat commented on Jun 8, 2023

    @Haringat

    That's sad because I thought there is a line between operator and keyword

    @FrameMuse They have to be both. If they were no keywords, nothing would stop people from e.g. naming a function new. That would, however, cause many problems.

    Here is an example, assuming that new was no keyword:

    function new() {
        // pretend that there is something useful here...
    }
    
    const foo = "bar";
    
    new `something${foo}`;

    If new was no keyword, that code would parse. However, defining the behavior of the last line would be difficult. (Is it an attempt to instantiate a template-string or is it using the new function as a tag?)

    Edit:
    I think it is not about looking at operators and keywords, but rather at looking at "what might make sense to overload?".
    We could overload pretty much anything, but overloading yield makes no sense, at it's entire purpose is contextual and only related to the generator it appears in. There is also not really a different interpretation I can think of that yield might do to different objects.

    Operator overloading is all about making objects behave how you would expect from looking at the code. So it should not be about making an operator overloadable because you can, but because there is a purpose you need it for to clean up your code.

    As mentioned above, for new it might be possible to overload it but there is no reason to do so, because new means "instantiate the class that follows". Making an object "behave like a class" makes little sense. Overloading it inside the class as C++ does only serves a need we do not even need to care about.

    () on the other hand has valid use-cases, as Kotlin showed (mostly for building DSLs).

  12. jhmaster2000 commented on Jun 13, 2023

    @jhmaster2000

    @jhmaster2000 Well, first of all: You cannot trap apply on objects using proxies. You would have to make every object, on which you might want to overload the () operator, a function, only to be able to trap apply. That would be possible, but it is a pain.

    As for new.target: I am highly against overloading new.

    Glad we agree on new, I still don't really understand your point with (), if you know you plan on making an object callable somewhere else in your code, you have no reason to just create it as a function?

    If you mean "it is a pain" just because a function declaration + prop attaching is more verbose than { ... }, you can just create an alias function, which honestly you should have anyways to signal that the function is going to be used as a callable object, i.e:

    const callable = (props = {}) => Object.assign(function() {}, props);
    // or if you want the default behavior to be error until you you apply your () overload:
    const callable = (props = { throw new Error("Not callable yet."); }) => Object.assign(function() {}, props)
    
    // use
    const obj = callable();
    const obj2 = callable({ x: 1, y: 2 });

    Perhaps callable could be provided as a built-in for convenience.

    Edit¹: As a bonus, this also allows you to have all types of functions as "callable objects", async, generator, both, etc. while going from a plain object to an attached () overload you can't do that, you're stuck with only regular synchronous function call overloading.

  13. FrameMuse commented on Jun 13, 2023

    @FrameMuse

    @jhmaster2000

    Edit¹: As a bonus, this also allows you to have all types of functions as "callable objects", async, generator, both, etc. while going from a plain object to an attached () overload you can't do that, you're stuck with only regular synchronous function call overloading.

    So we go from "everything is object" to "everything is function" :)

  14. jhmaster2000 commented on Jun 14, 2023

    @jhmaster2000

    @jhmaster2000

    Edit¹: As a bonus, this also allows you to have all types of functions as "callable objects", async, generator, both, etc. while going from a plain object to an attached () overload you can't do that, you're stuck with only regular synchronous function call overloading.

    So we go from "everything is object" to "everything is function" :)

    No? Only "objects" which you plan on overloading the () operator on, which realistically is going to be rare, I don't see your point, oh and also, on second thought, you can even convert plain objects into "callable objects" as functions to overload (), that is essentially what the callable function I've shown above does already, only instead of passing a new object you can also pass existing ones:

    // scenario: some library api which expects a callable to inject extra `()` behavior on
    function someLibraryApi(arg) {
      if (typeof arg === 'object') {
        // convert to callable
        arg = callable(arg);
      }
      // apply () overload
      arg['operator()'] = ...;
      // note: Additionally, currently as the proposal stands,
      // there isn't even a way to dynamically overload operators in existing objects,
      // for good reasons and this is unlikely to change,
      // so this whole use-case is actually flawed to begin with...
    }

    So with that last note in mind, we're left with only use-cases defined at object creation, which, if you're creating something you plan to call, you should just make it a function anyways? What kind of behavior () overloads could declare that couldn't just be done in the body of the function itself when declaring it?

  15. Haringat commented on Jun 14, 2023

    @Haringat

    @jhmaster2000 That callable creates a new function and assigns all properties from the given object. It does not make the object itself callable. That distinction is important because

    1. x !== callable(x)
    2. Inherited properties and methods are not taken over as this is just a callable shallow clone and its prototype is Function.prototype.

    Edit: Why would we be stuck with synchronous functions? When we overload () what would prevent us from using an asynchronous function to overload it?

  16. Haringat commented on Jun 14, 2023

    @Haringat

    So with that last note in mind, we're left with only use-cases defined at object creation, which, if you're creating something you plan to call, you should just make it a function anyways?

    Simple (and I just hinted at that in the comment above): Inheritance. With making something a function you automatically set its prototype fix to Function.prototype and there is nothing you can do about it.

  17. jhmaster2000 commented on Jun 15, 2023

    @jhmaster2000

    @jhmaster2000 That callable creates a new function and assigns all properties from the given object. It does not make the object itself callable. That distinction is important because

    1. x !== callable(x)
    2. Inherited properties and methods are not taken over as this is just a callable shallow clone and its prototype is Function.prototype.

    Edit: Why would we be stuck with synchronous functions? When we overload () what would prevent us from using an asynchronous function to overload it?

    1. Irrelevant unless the proposal changes to allow dynamic attachment of operators, which almost certainly not going to happen, its too volatile and near impossible to optimize otherwise. As it currently stands you will be declaring operators at the time you declare x itself so there's no reason () operator would be different.
    2. That's a good catch, just something I didn't account for, but it is very much fixable with ease, you can set the prototype, revised version:
    const callable = (obj = {}) => {
      const fn = function() {};
      Object.setPrototypeOf(fn, Object.getPrototypeOf(obj));
      Object.assign(fn, obj);
      return fn;
    }

    Regarding the Edit, regardless of what the prototype is set to, internally the engine will still know what kind of function your "object" is, it needs to in order to work, so typeof can correctly return 'function' and other things, so if you internally want your "callable object" to be an AsyncFunction you can do so by making fn above async, how would you do so in the declaration of a () overload? It needs to be at static analysis time, so arguments/return value don't work, you'd need to declare distinct overloads incompatible between themselves for each one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions