Rodrigo Casanova Rodrigo Casanova - 3 months ago 13
Javascript Question

Strange behavior and multiple instances using Object.create on literal objects

I'm learning oop in JS and I know that the "right way" to do multiple instances objects is using

var object = function(){}
but while I'm learning I'm doing different things to learn how JS works.
I'll cut down to the chase, hiding piece of code unrelated to this question.

The thing is, if I use the following code, when I create two instances of the Selectable object, I get the same id property in the both of them.

var Selectable = {
create: function(type) {
Object.create(this);
this.type = type;
this.id = Math.random().toString(36).replace(/[^a-z]+/g, '').substring(0, 5);

return this;
}
};


But, if I do this:

var Selectable = {
create: function(type) {
var _T = Object.create(this);
this.type = type;
this.id = Math.random().toString(36).replace(/[^a-z]+/g, '').substring(0, 5);

return Object.create(_T);
}
};


They get different id properties.
I did read about the Object.create() function and what I learned is that it creates a new object with the "prototype" of the model object used. But why this works when I create an object using two Object.create() functions in a row?

Answer
var Selectable = { 
create: function(type) { 
Object.create(this); 
this.type = type; 
this.id = Math.random().toString(36).replace([^a-z]+/g, '').substring(0, 5);
 return this; 
} 
};

alert(selectable.create());

Your function finally does return this. But this isnt the created object, its still the selectable. Also you clone the object before you've set its id and type. Do:

var selectable={
create:function(type){
obj=Object.create(this);
obj.type=type;
obj.id=whatever;
return obj;
};
}
Comments