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?
Missing. Really no. Your constructor function does nothing more than init. It is more or less antipattern.
init
, , , ( ), reset. JS : .constructor(). , , , ( ).
.constructor()
, init , . , , , ( ) , , , , init (, ). , , yagni.
javascript, , , , . , :
function Person (name) { this.name = name; } function Accountant () {} Accountant.prototype = new Person('');
, Accountant, :
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.
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 , .