0

Basically, I found the javascript library where the API uses some object literal. I am trying to figure out how to separate them on different javascript files for easier reading. There is the file that has like 30 different functions nested in a single object... I am trying to separate them. The example below is simplified to show my point.

BasicGame.Game.prototype = {

var1: function () { blah blah},
var2: function () { blah blah},
var3: function () { blah blah},
var4: function () { blah blah}
}

How an you take out var3 and var4 and put in them in another object literal that shares same Basic.Game object? If I wrote BasicGame.Game again, it would overwrite the original object literal.

2

2 Answers 2

2

You can write BasicGame.Game.prototype.var3 = function() { } in another file and it won't overwrite the functions already in there.

For example, file1.js:

BasicGame.Game.prototype = {
    var1: function () { blah blah},
    var2: function () { blah blah}
}

And file2.js:

BasicGame.Game.prototype.var3 = function () { blah blah};
BasicGame.Game.prototype.var4 = function () { blah blah};

Just make sure that file1.js is included first or use the dot notation for both files.

Sign up to request clarification or add additional context in comments.

2 Comments

That would work. But is it possible to make another object literal? Seems a bit inelegant to write BasicGame.Game.prototype.somevar over and over again.
@user1142285 You could store BasicGame.Game.prototype in a temporary variable and do proto.var3 = function() { bla blah }. The only alternative is using a library like jQuery to merge object literals.
1

You can augment Object with the following code:

Object.defineProperty(Object.prototype, "partial", {
    enumerable: false,
    configurable: false,
    set: function (value) {
        if (value.constructor === Object) {
            for (prop in value) {
                if (value.hasOwnProperty(prop)) {
                    this[prop] = value[prop];
                }
            }
        }
        return this;
    },
    get: function () { return this;}
});

Then you can use this augment to add literals to any object like so:

//first file
BasicGame.Game.prototype = {

    var1: function () { alert("blah blah"); },
    var2: function () { alert("blah blah"); },
}

//second file
BasicGame.Game.prototype.partial = {

    var3: function () { alert("blah blah"); },
    var4: function () { alert("blah blah"); }
}

var game = new BasicGame.Game();

now game will show all four properties as they "shine through" its constructor's prototype.

1 Comment

Whoa, I am impressed by this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.