goldfidget;1142360 wrote:So if I'm getting this correctly you should be able to just extend the Object object to give everything the extend method.
Yes. In fact, that's how prototype objects were designed to be used. Though, eventually developers started to notice a problem. When you iterate over an object, you get not only its own properties, but everything attached to the prototype as well.
Object.prototype.extend = function() {
function F() {}
F.prototype = this;
return new F;
}
var abc = {a: 'a', b: 'b', c: 'c'};
for (var p in abc) {
alert(p); // alerts a, b, c, and extend
}
One way developers suggested avoiding this problem was to use the hasOwnProperty method, and use it religiously.
for (var p in abc) {
if (abc.hasOwnProperty(p)) {
alert(p); // alerts a, b, c
}
}
And some developers did that, but not everyone did, and developers started to painfully realize that if they attached new properties to the built-in prototypes, then their code would likely break someone else's code, because you never know if all the other code on a page checks hasOwnProperty or not. Today, it's considered taboo to alter the built-in prototypes. If you can avoid it, then your code will be safer and more portable.
goldfidget;1142360 wrote:Would there be a way to pass an object literal to the extend method and have all it's members added to the child object
There sure is.
var BaseObj = {
extend: function ([color=green]newProperties[/color]) {
function F() {}
F.prototype = this;
[color=green]var subtype =[/color] new F;
[color=green]if (newProperties) {
for (var p in newProperties) {
subtype[p] = newProperties[p];
}
}
return subtype;[/color]
}
};
goldfidget;1142360 wrote:Why do I have to add the method to Object.prototype rather than simply Object?
When you make a new instance of something — [font=courier]var instance = new Constructor()[/font] — remember that the instance inherits from Constructor.prototype. Object is the same way. "Object" is the constructor function, and Object.prototype is the object from which all instances inherit.