简体   繁体   中英

How to rewrite this IIFE into an ES6 class?

So I have this IIFE, and for the sake of consistence with other ES6 classes I rewrote for a plugin, I also want to rewrite this into using ES6 Class syntax. Can anyone show me how to do it?

Foo = (function(){
    Foo.bar = function(a, b){
        baz = new this(a, b);

        return baz;
    }

    function Foo(a, b){
        this.a = a;
        this.b = b;
    }

    return Foo;

})();

It would be a simple

class Foo {
    constructor(a, b) {
        this.a = a;
        this.b = b;
    }
    static bar(a, b) {
        return new this(a, b);
    }
}

The function created by the IIFE can be just as well created using a plain function declaration and property assignment:

 function Foo(a, b) { this.a = a; this.b = b; } Foo.bar = function(a, b) { baz = new this(a, b); return baz; } var foo = new Foo('FooA', 'FooB'); console.log(foo.a + ':' + foo.b); var baz = Foo.bar('BazA', 'BazB'); console.log(baz.a + ':' + baz.b); 

Using the class syntax :

 class Foo { constructor(a, b) { this.a = a; this.b = b; } static bar(a, b){ baz = new this(a, b); return baz; } } var foo = new Foo('FooA','FooB'); console.log(foo.a + ':' + foo.b); var baz = Foo.bar('BazA', 'BazB'); console.log(baz.a + ':' + baz.b); 

Unfortunately I can't actually run this code as the site I'm currently on has SOE versions of Firefox and IE that don't recognise the class syntax. So please update if it's faulty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM