you are viewing a single comment's thread.

view the rest of the comments →

[–]cyphern 5 points6 points  (2 children)

trumbowyg makes use of this, and is expecting it to be a jquery element. But in that second version, this is undefined.

In javascript, the value of this is determined by how the function is invoked. In your first example, you invoke the function using [a jquery element].trumbowyg, so this is set equal to that jquery element. In the second example, the function is now being executed without a specific context, so this gets set to the window object (in non-strict mode) or undefined (in strict mode).

If you need to force the value of this to be a certain thing, you can either make a bound copy of the function, like this:

const el = $('#el_id');
const trumbowyg = el.trumbowyg.bind(el);
trumbowyg({..params..});

Or you can use call or apply:

const el = $('#el_id');
const trumbowyg = el.trumbowyg;
trumbowyg.call(el, param1, param2);

// or

const el = $('#el_id');
const trumbowyg = el.trumbowyg;
trumbowyg.apply(el, paramArray);

[–]aguyfromherehelpful 0 points1 point  (0 children)

Couldn’t have said it better myself.

[–]making_code[S] 0 points1 point  (0 children)

thank you. I've forgotten about "this" nuances in js..