0

There are plenty of questions about ECMAScript 6 fat arrows or extending jQuery's prototype, but I have found none which explains how they work together with an example.

Not using fat arrows, I usually do this to create a new function for use with jQuery, for instance:

$.fn.populate = function (items /*read from .json*/) {

    console.log(items); //JS object passed as param
    console.log(self); //Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
    console.log(this); //jQuery object with $('#populate-me')

    $this = $(this);
    Object.entries(items).forEach(function (pair) {
        $this.append('<div>' + pair[0] + ' - ' + pair[1] + '</div>');
    });
};

//usage
$('#populate-me').populate(items);

Is ther a way of doing that WITH fat arrows? Like, say:

$.fn.populate = (items /*read from .json*/, maybe) => {

    console.log(items); //JS object passed as param
    console.log(maybe); //undefined
    console.log(self); //Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
    console.log(this); //Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}

    $this = $(SOMETHING TO ACCESS #populate-me);
    Object.entries(items).forEach(function (pair) {
        $this.append('<div>' + pair[0] + ' - ' + pair[1] + '</div>');
    });
};

or should I stick to non-fat-arrow functions?

thanx

Scaramouche
  • 3,188
  • 2
  • 20
  • 46
  • Not possible like that because `this` will be inherited from the outer scope, rather than being taken from the calling context. Ugly way to do it would be to explicitly pass the collection in an argument – CertainPerformance Oct 31 '18 at 02:41
  • @CertainPerformance; what do you mean by "the collection"? – Scaramouche Oct 31 '18 at 03:31
  • The jQuery collection. eg `$('div')` is a jQuery collection of `
    `s
    – CertainPerformance Oct 31 '18 at 03:33
  • @CertainPerformance; do you mean `$('#populate-me').populate(items, $('#populate-me'));`?? ugly would fall short – Scaramouche Oct 31 '18 at 03:49
  • `const $populateme = $('#populate-me'); $populateme.populate(items, $populateme)` Pass the calling context manually, don't duplicate the collection again. (bad idea either way, just use a regular function instead) – CertainPerformance Oct 31 '18 at 03:51

0 Answers0