Beginner JavaScript Object.create Question

skrasms's icon

I'm new to using JavaScript in an object-oriented way, but I saw an example that made Object.create seem pretty straightforward. Then when I tried using it on my own, the results were not what I expected. It seems that I can only create one object using Object.create from my original "prototype" object.

This is a stripped down example to show what I don't understand:

var someObject = {
    color: {
        r: 1.0,
        g: 1.0,
        b: 1.0,
        a: 1.0
    }
};

var obj1 = Object.create(someObject); //Make an instance of someObject
var obj2 = Object.create(someObject); //Make a second instance of someObject

obj1.color.r = 5;
obj2.color.r = 30;

post(obj1.color.r + "n");
post(obj2.color.r + "n");

My expectation for that code was that I would end up with two different objects, each with its own color.r property. Thus, I would see 5 followed by 30 in the Max console window. Instead, I see 30 followed by 30.
Are obj1 and obj2 the same object? How can I easily separate them?

skrasms's icon

I think I'm understanding a little better now.

obj1 and obj2 are two different objects, but creating obj1 creates the color object which is then passed by reference instead of recreated for each someObject instance. So, obj1.color and obj2.color point to the same object. A solution is to add a function to break the reference by creating a new internal object:

var someObject = {
    color: {},
    init: function () {
        this.color = {    //create a new object for color
            r: 1.0,
            g: 1.0,
            b: 1.0,
            a: 1.0
        }
        return (this);
    }
};

var obj1 = Object.create(someObject).init();
var obj2 = Object.create(someObject).init();

obj1.color.r = 5;
obj2.color.r = 30;

post(obj1.color.r + "n");
post(obj2.color.r + "n");

That is working for me, though it's less clean.

moss's icon

As a long time JavaScript programmer and not knowing that function you got my curiosity. The function is described here:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create

I do not know what the intention of Mozilla was to introduce this function. From looking at the code example at the end of the page you actually see what it does. It creates an "unamed sub-class" of the given object. Therefore it is NOT for creating new objects.

For writing nice code with "classes" and objects I always use the following style:

//
// A demo class
//

function MyCoolClass (param1, ..., param2)
{
    this.param1 = param1;
    ...
    this.param2 = param2;
}

MyCoolClass.prototype.myCoolFunction1 = function ()
{
    // Do cool stuff
};

MyCoolClass.prototype.myCoolFunction2 = function (p1, p2, ..., pN)
{
    // Do more cool stuff
}

//
// Usage
//

var thisIsAnInstance = new MyCoolClass ('Klaus', 'Maus', 4711);

thisIsAnInstance.myCoolFunction1 ();
thisIsAnInstance.myCoolFunction2 (aParam, 'Whatever');