Using Prototype in JS

2

I need help with using Prototypes, I'm trying to organize and maintain a cleaner code and can re-use my classes at other times ... And in research, using Prototype seems to be advantageous ... (I can have corrected wrong, correct me ...)

Firstly I will put my code below and follow my doubts ...

var Model = function(hello) {
    this.hello = hello; 

    //meu teste
    this._init();
}

Model.prototype = function(){
    var _init = function(){
        console.log("Init...");

        this.helloWorld();
    },

    _helloWorld = function(){
        alert(this.hello)
    };

    return {
        helloWorld : _helloWorld
    };
}();

1st Doubt: Inside my Builder how could I call my "_init" function? Since it is private, I would like to have the first call inside the constructor. In my example above, I made the call via "this._init ()", but I had the error:

Uncaught TypeError: this._init is not a function

2nd Doubt: Within my "_init" function will I be able, and I will have calls from other methods, in this example: "_helloWorld", the form I did would work? Or the right way?

Thank you.

    
asked by anonymous 10.08.2018 / 12:43

1 answer

2

The point is that you have not exported the _init function to the prototype body, just as you did with the helloWorld function; so it will only exist in the local scope of the function that defines prototype , but not in the object itself. To solve, simply export the function:

var Model = function(hello) {
    this.hello = hello; 

    // Chamando o método "init"
    this.init();
}

Model.prototype = function(){
    var _init = function(){
        console.log("Init...");

        this.helloWorld();
    },

    _helloWorld = function(){
        console.log('Hello ' + this.hello)  // Alterei para console.log para facilitar a visualização
    };

    return {
        init: _init,  // Exportanto para o prototype a função _init
        helloWorld : _helloWorld
    };
}();

const m = new Model('world');

But in ES6 the class structure has been defined in JavaScript and has a very good support already, except in the family IE. With it, you can do:

class Model {
  constructor(name) {
    this.name = name
  }
  
  hello() {
    console.log('Hello ' + this.name)
  }
}

const m = new Model('world')

m.hello()

You can read more about the classes in MDN: Classes in JavaScript .

Related:

10.08.2018 / 14:06