Skip to content

callable classes #283

Open
Open

Description

@nyuichi

According to @yosuke-furukawa san, something like python's __call__ method (that's for objects, and in this case for classes) will be useful if introduced.

Many nodejs modules (ex. https://github.com/flatiron/nock) are providing a kind of tricky API, that is a function object which returns new instances every time it's called. They are alternative style of class and JSX doesn't have a means of getting access to these functions.
I suggest JSX introduce a special method called __new__, which enables users to call classes directly as if it is an object.

var nock = require('nock');

// creating a nock object via function call, not `new` operation
var couchdb = nock('http://myapp.iriscouch.com');
// A class that has a `__new__` method can called as if an object
native class nock {
    static function __new__ (url : string) : scope;
} = "require('nock')";

class _Main {
    static function main (args : string[]) : void {
        var scope = nock();
    }
}

Activity

  1. yosuke-furukawa commented on Nov 25, 2013

    @yosuke-furukawa

    👍

  2. kazuho commented on Dec 4, 2013

    @kazuho
    Member

    No objections under the premise that the feature will be limited to native classes.

    Besides, I believe that the attribute should be named __call__ instead of __new__ since the role of the object (that is invoked as a function) would not be limited to creating new objects.

  3. nyuichi commented on Dec 4, 2013

    @nyuichi
    MemberAuthor

    @kazuho

    Another idea is that use anonymous method to check this kind of attribute, see

    class nock {
        static function (url : string) : scope;
    } = "require('nock')";

    Fundamentally there's no difference between the semantics, only the syntaxes differ. From the aspect of extensibility I prefer __call__ (or __new__) but I guess it'd be not JSXish, rather too pythonic.

  4. kazuho commented on Dec 4, 2013

    @kazuho
    Member

    @wasabiz
    What about introducing both __new__ and __call__, since they are different invocation methods.

    IMO we should support definitions like below.

    native class Foo {
        function __new__() : Bar;
        function __call__() : Bar;
        // static function __new__(); // cannot be defined, since it is the same as `function constructor`
        static function __call() : Bar;
    }
    

    In the above snippet, new (new Foo()), (new Foo())(), and Foo() are permitted.

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

      ⌂ Proxy