[Javascript] Kann mir jemand diese Funktion erklären?

B

BloodSteam

Guest
Hallo,
Ich hab eine Funktion auf Stackoverflow gesehen jedoch weiß Ich nicht genau wie es funktioniert.
javascript - Advantages of createElement over innerHTML? - Stack Overflow

Code:
  function isArray(a){
    // Wieso braucht man hier ein Object.prototype ? <-------------------------------------
    return Object.prototype.toString.call(a) === "[object Array]";
  }


  function make(desc){
    if( !isArray(desc) ){
      // Wieso braucht man hier ein Object.prototype ? <-------------------------------------
      return make.call(this, Array.prototype.slice.call(arguments));
    }


    let name = desc[0];
    let attributes = desc[1];


    let el = document.createElement(name);


    let start = 1;
    if( typeof attributes === "object" && attributes !== null && !isArray(attributes) ){
      for( let attr in attributes ){
        el[attr] = attributes[attr];
      }
      start = 2;
    }


    for( let i = start; i < desc.length; i++ ){
      if( isArray(desc[i]) ){
        el.appendChild( make(desc[i]) );
      }else{
        el.appendChild(document.createTextNode( desc[i] ));
      }
    }


    return el;
  }
 
Weil der Typ des Objects abgefragt wird, ToString() von 'Object' bei Arrays durch eine eigene ToString-Methode überschrieben wird und Object.ToString() nur den Typ 'object' zurück gibt.

Array.toString() -> Inhalt des Arrays

var object= {1: 2}; -> object.toString() -> [object Object]

Object.prototype.toString.Call(object); -> [object Array]

Edit:
Und weil typeof() Probleme machen kann.

typeof - JavaScript | MDN
 
Ich hab es durch dies ersetzt. Funktioniert genau so.
Code:
x instanceof Array

Code:
function create(x){
  let element = x[0],
      child = x[1],
      node = document.createElement(element),
      i = 1;


  if (typeof child === "object" && child !== null && !isArray(child)) {
    for (var attr in child) node[attr] = child[attr];
    i = 2;
  }


  let l = x.length;
  for (; i < l; i++) {
    if( isArray(x[i]) ) node.appendChild( create(x[i]) );
    else node.appendChild( document.createTextNode(x[i]) );
  }


  return node;
}


function innerNode(newNode, node) {
  node.parentNode.insertAfter(newNode, node);
}
 
If-Cases und Schleifen ohne Klammern fliegen früher oder später jedem mal um die Ohren.

Und wenn es schon so super toll fancy sein muss, warum nicht gleich
Code:
node.appendChild(  isArray(x[i]) ? create(x[i]) : document.createTextNode(x[i]) );

:P
 
Zurück