Reputation: 11807
I was looking at some code, and just to make sure I wasn't losing my mind with missing the obvious as this looks like to me, there is nothing gained. Seems like a wasteful usage of $.extend() but perhaps someone can shed some light on something I might be missing with inheritance.
So, we have this.
_letsCreateNameSpace('US.somenew.obj');
//this is based on S.stoyanov namespace pattern, what this _letsCreateNameSpace does.
then I seen this in some code, and it didn't make sense to me.
US.somenew.obj = function(){
// some this var assignments.
this.blah = $foo;
}
// this usage of extend escapes me. I don't see a need at this point here.
$.extend(US.somenew.obj.prototype, {
// a bunch of new methods
}
I do not see at all the benefit of using $.extend() instead of just the following, as there is no extending anything but itself.
US.somenew.obj.prototype = {
// a bunch of new methods
}
there is no 'deep' extend or anything.. just looks like a verbose way of extending a prototype for no reason.
Am I missing something? Is there some "forest behind the tree's" methodology I am missing here?
Upvotes: 0
Views: 58
Reputation: 25322
$.extend
will copies to the prototype
the methods given without overwrite the prototype
object itself. So for instance, if you have:
// inheritance
US.somenew.obj.prototype = myproto;
US.somenew.obj.prototype = {
// you lost the inheritance with `myproto`, here
}
Using $.extend
will prevent that. Plus, you won't lose some default property. For example, the constructor
:
US.somenew.obj = function () {};
US.somenew.obj.prototype = {};
var o = new US.somenew.obj();
console.log(o.constructor === US.somenew.obj) // false, in that case is `Object`
Where:
US.somenew.obj = function () {};
$.extend(US.somenew.obj.prototype, {});
var o = new US.somenew.obj();
console.log(o.constructor === US.somenew.obj) // true
Upvotes: 3
Reputation: 816472
I think the only benefit is to keep the original prototype object intact instead of overwriting it with a new object.
The constructor
property will refer to the correct function (US.somenew.obj
) instead of referring to Object
. Of course you could just reassign .prototype.constructor
correctly (and this is done quite often), but you can avoid this with extending the existing object.
From a coding style point-of-view it seems to make sense as well: Usually you don't want to replace the prototype, you want to add properties to it.
Upvotes: 1