What are the benefits of having a separate init function on objects?

I mean code like this:

 function MyObject(x, y, z) {
     this.init(x, y, z);
 }
MyObject.prototype = {
    constructor: MyObject,
    init: function(x, y, z) {
        // actually use x, y, z
    },
    other methods
};

Why not just have an init method and do all the initialization in the constructor?

+4
source share
2 answers

Missing. Really no. Your constructor function does nothing more than init. It is more or less antipattern.

, , , ( ), reset. JS : .constructor(). , , , ( ).

, init , . , , , ( ) , , , , init (, ). , , yagni.

0

javascript, , , , . , :

function Person (name) {
    this.name = name;
}

function Accountant () {}

Accountant.prototype = new Person('');

, Accountant, :

var x = new Accountant();

, :

x.name = 'Andy';

. , , , .

- , , , :

function new_person (name) {
    var self = {};
    self.name = name;
    return self;
}

function new_accountant (name) {
    var self = new_person(name);
    return self;
}

. , new.

, , - , init, , :

function Person (name) {
    this.init(name);
}

Person.prototype.init = function (name) {
    this.name = name;
}

function Accountant (name) {
    this.init(name);
}

Accountant.prototype = new Person('');

, , . javascript, . init , .

0

All Articles