Home > front end >  My class will return undefined if I call its method
My class will return undefined if I call its method

Time:11-17

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:

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"}

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

toAppend doesn't have a return value. You are assigning variable "jorge" with what toAppend returns -> semantically nothing, undefined. toAppend appears to be a method that shouldn't have a return value, but you want it to behave as a fluent interface. In such case, just return "this"

toAppend(appends){
  this.node.appendChild(appends);
  return this;
}

When you assign only the constructor, you are assigning the initialized object. That's why you obtain what you call "weird" when you assign only the constructor. That's not weird, but expected.

The downvoter should also explain what is incorrect in my answer.

  • Related