Javascript 1.9.3 / ECMAScript 5 introduces Object.create
, which Douglas Crockford amongst others has been advocating for a long time. How do I replace new
I think the main point in question - is to understand difference between new
and Object.create
approaches. Accordingly to this answer and to this video new
keyword does next things:
Creates new object.
Links new object to constructor function (prototype
).
Makes this
variable point to the new object.
Executes constructor function using the new object and implicit perform return this
;
Assigns constructor function name to new object's property constructor
.
Object.create
performs only 1st
and 2nd
steps!!!
In code example provided in question it isn't big deal, but in next example it is:
var onlineUsers = [];
function SiteMember(name) {
this.name = name;
onlineUsers.push(name);
}
SiteMember.prototype.getName = function() {
return this.name;
}
function Guest(name) {
SiteMember.call(this, name);
}
Guest.prototype = new SiteMember();
var g = new Guest('James');
console.log(onlineUsers);
As side effect result will be:
[ undefined, 'James' ]
because of Guest.prototype = new SiteMember();
But we don't need to execute parent constructor method, we need only make method getName
to be available in Guest.
Hence we have to use Object.create
.
If replace Guest.prototype = new SiteMember();
to Guest.prototype = Object.create(SiteMember.prototype);
result be:
[ 'James' ]