I came across this code for stripping Marketo forms of their included stylesheets. Let's assume that the code author is a super senior engineer. Array.from() could have been used instead of defining arrayFrom (functionally at any rate), so why use the latter?
For my part I'm trying to understand the arrayFrom definition (first line of the codeblock):
- bind() sets
thisto the provided value, here[].slice(why?) - call() allows us to call
getSelectionwith thethisvalue bound bybind. - getSelection() returns a Selection object (or string in Firefox) of the selected text. This I'm unsure about.
In its use,
arrayFromgets passed an array (or NodeList) of stylesheets and returns an array of the same stylesheets (a shallow copy thereof?) no differently than ifArray.fromwere used, so the functional bit ofbindandcallmust be to alter thethisvalue in a desirable way. Not sure how that acts on[].slicethough.
Anyone? I'm clearly missing something.
const arrayFrom = getSelection.call.bind([].slice);
// remove element styles from <form> and children
const styledEls = arrayFrom(formEl.querySelectorAll("[style]")).concat(
formEl
);
styledEls.forEach(function (el) {
el.removeAttribute("style");
});
// create an array of all stylesheets in document
const styleSheets = arrayFrom(document.styleSheets);
// loop through stylesheets and check for ownerNode properties on each
styleSheets.forEach(function (ss) {
if (
//array of <link/> elements tied to stylesheets
[mktoForms2BaseStyle, mktoForms2ThemeStyle].indexOf(ss.ownerNode) !=
-1 ||
formEl.contains(ss.ownerNode)
) {
ss.disabled = true;
}
});
Nowadays we would just use
Array.from. But your questions are about the construct that is used:First of all, this has nothing to do with
getSelection, as the expression is not binding that, but thecallfunction. Thiscallfunction is on theFunctionprototype, so the above leads to the same result as:callis a function that allows one to call another function with the possibility to provide a this-argument to it. Here we define that the function to be called should beslice. The first argument we will provide toarrayFromwill be like the first argument we would provide tocall, i.e. the object on whichsliceshould be called. This gives it a similar behaviour asArray.from.It may help to replace
bindby this function that does a similar thing:It is confusing, but we invoke
callwithcallso that we can provide athisargument to it (defining the function we want to call), making the second argument thethis-argument thatcall(the first one) deals with.