0

I was setting up a little helper function like so:

if (!Object.prototype.__construct) {
Object.prototype.__construct = function() {
    if (typeof arguments[0] !== 'object' ||
        arguments.length === 0) return;
    for (var name in arguments[0]) {
        if (arguments[0].hasOwnProperty(name))
            this[name] = arguments[0][name];
    }
}}

if (!Object.prototype.__)
    Object.prototype.__ = Object.prototype.__construct;

It is invoked like such:

function Foo(props) {
    this.__(props); // or this.__construct(props);
    ...
}
var foo = new Foo({a:1,b:2,c:3});

As you can see, it just acts as a simple constructor. However when using it with EaselJS, specifically SpriteSheet() I get an error of Uncaught TypeError: Cannot call method 'slice' of undefined. Here is a snippet of code illustrating where the issue arises:

var ss = new SpriteSheet({
    images: ...,
    frames: {
        ...
    },
    animations: {
        walk: [0, 1, "walk", 8] // <-- Error caused here.
    }
});

So, is there a better way to go about writing an Object prototype like this, which will not cause a (presumably) clash with Easel? Or possibly a better way altogether? (Native?). Thanks.

grep
  • 3,986
  • 7
  • 45
  • 67
  • Extending the `Object` prototype is a bad idea. – zzzzBov Nov 09 '12 at 20:10
  • @zzzzBov Could you please elaborate or link me to some reference? – grep Nov 09 '12 at 20:11
  • After a very brief amount of searching, I've found [this article which explains some of the pros and cons](http://javascriptweblog.wordpress.com/2011/12/05/extending-javascript-natives/), "Extending Object.prototype 'is Verboten' For some or all of these reasons, the JavaScript community has considered Object.prototype extensions taboo for several years..." – zzzzBov Nov 09 '12 at 20:18
  • Basically, if you start overriding `Object.prototype` you can expect libraries (such as jQuery) to start failing, and devs that view your code to start hating you. – zzzzBov Nov 09 '12 at 20:20
  • Thanks for the reference. Same reasons I would imagine. However the convenience this brings for my small project is really nice. Any ideas on how resolve besides not doing it, ha? – grep Nov 09 '12 at 20:29
  • Your function is not a constructor function, it simply extends an object with another object's properties. jQuery has this as [`jQuery.extend`](http://api.jquery.com/jQuery.extend/), Underscore has this as [`_.extend`](http://underscorejs.org/#extend), so I would follow their lead and leave it as a static function that merges properties into the first object parameter provided. – zzzzBov Nov 09 '12 at 20:42

0 Answers0