Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Classes: Wrap method implementation in another function

Trying to figure out the syntax for doing something like this using ES6 classes:

function Component() {

}

Component.prototype.render = style(function() {

});

This is what I have so far:

class Component {

  constructor() {
    super()
  } 

  render style(() {

  });
}

Any ideas?

like image 987
Matt Avatar asked Oct 12 '25 17:10

Matt


2 Answers

Since class is just syntactic sugar, this should work:

class Component {
    constructor() {
        super()
    } 
}

Component.prototype.render = style(function() {
});

here is what torazaburo already showed you, http://www.es6fiddle.net/i67l1pjr/.

var style=function(fun){
  // do something with fun

  return fun
}

class Component {
    constructor() {
        super()
    }       
}

Component.prototype.render = style(function() {
  console.log('i am invoked');
});


var x=new Component;
x.render();

I assume your style function is just like the one i have defined, now in this case, you can easily acheive the desired result(creating a function returned by another function) using the old way of defining a method.

USing ES-6 syntax

Now as we know es6 classess are just syntactic sugars , and we must be able to acheive everything using classes, as we did before.

see this. http://www.es6fiddle.net/i67l1d4e/

var style=function(fun){
  // do something with fun

  return fun
}

class Component {
    constructor() {
        super()
    } 


  render (){    // this is the new render function, you wanted to define

    var fun =style(function() {
      console.log('i am invoked');
       });

    return new fun();
  }

}

var x=new Component;
x.render();

Now both of these ways, do the same thing.. its just a different syntax added by ES-6

like image 41
Community Avatar answered Oct 14 '25 11:10

Community



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!