Monday, 15 April 2013

inheritance - Can I construct a JavaScript object without using the new keyword? -



inheritance - Can I construct a JavaScript object without using the new keyword? -

here i'd do:

function a() { // ... } function b() { // magic, homecoming new object. } var c = b(); c instanceof b // -> true c instanceof // -> true b instanceof // -> true

is possible? can create b instance of a hooking a prototype chain have new b(), i'm trying avoid. want possible?

update: sense might possible judicious utilize of b.__proto__ = a.prototype. i'm going experiment more after work.

update 2: below seems closest can get, plenty me. interesting answers.

function a() { // ... } function b() { if (!(this instanceof arguments.callee)) { homecoming new arguments.callee(); } } b.__proto__ = a.prototype var c = b(); c instanceof b // -> true c instanceof // -> false b instanceof // -> true

update 3: found wanted in blog post on 'power constructors', 1 time added essential b.__proto__ = a.prototype line:

var object = (function() { function f() {} homecoming function(o) { f.prototype = o; homecoming new f(); }; })(); function a(proto) { var p = object(proto || a.prototype); homecoming p; } function b(proto) { var g = object(a(proto || b.prototype)); homecoming g; } b.prototype = object(a.prototype); b.__proto__ = a.prototype; var c = b(); c instanceof b // -> true c instanceof // -> true b instanceof // -> true a() instanceof // -> true

you can utilize pattern:

function someconstructor(){ if (!(this instanceof someconstructor)){ homecoming new someconstructor(); } //the constructor properties , methods here }

after can do:

var myobj = someconstructor();

in add-on (rather old) answer: can utilize module pattern create object:

function person(name, age, male) { name = name || 'unknown'; age = age || 0; function get() { homecoming ['this person called ', name, (!male ? ', her' : ', his'),' age ', age].join(''); } function setage(nwage) { age = nwage; } homecoming object.freeze({get: get, setage: setage}); } // usage var jane = person('jane', 23) ,charles = person('charles', 32, 1) ,mary = person('mary', 16); console.log(jane.get()); //=> person called jane, age 23 mary.setage(17); console.log(jane.get()); //=> person called mary, age 17

here's jsfiddle date functionallity created using pattern.

javascript inheritance prototype constructor

No comments:

Post a Comment