Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My class will return undefined if I call its method

what I’m trying to do is a class that creates an object, appends other objects and adds content to it without having to write several lines of

var obj = document.createElement('input');
obj.value = 'this value';
obj.appendChild(anotherObject)

here is the code:

class gerarNode{
    constructor(input){
        this.nodetype = input;
        this.node = document.createElement(input);
    }
    toAppend(appends){
        this.node.appendChild(appends);
    }
}

what I expect in the browser console:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var jorge = new gerarNode('div').toAppend(anotherNodeObject)
// Object {"nodetype": "div", etc, etc}

what I get:

var jorge = new gerarNode('div').toAppend(anotherNodeObject)
// undefined

but the weirdest is, if I call only the constructor method, it will return a "div" object just as I wanted, it just not works if I call any method in the class

var jorge = new gerarNode('div')
// Object {"nodetype": "div"}

>Solution :

If you don’t execute a return statement in a function, it returns undefined.

To implement a fluent interface, all the modification functions should return this.

class gerarNode {
  constructor(input) {
    this.nodetype = input;
    this.node = document.createElement(input);
  }
  toAppend(appends) {
    this.node.appendChild(appends);
    return this;
  }
}

let anotherNodeObject = document.createElement("div");
var jorge = new gerarNode('div').toAppend(anotherNodeObject);

console.log(jorge);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading