Inheritance Fortunately, most browsers now support the Object.create
method. This method takes an existing object as a parameter. It returns a new object that has the existing object assigned as its [[Prototype]]
. Even more fortunately, this method is quite easy to create for those environments that do not support it:
if(typeof Object.create !== "function") { Object.create = function (o) { function F() {} F.prototype = o; return new F(); }; } var foo = { name: "foo", sayHello: function() { alert("hello from " + this.name); } };
foo.sayHello();
....
var bar = Object.create(foo);
bar.sayGoodbye = function() {
alert("goodbye from " + this.name);
}
bar.sayHello();
bar.sayGoodbye();
Method Two for creating inheritance: extend
function extend(obj, props) {
for(prop in props) {
if(props.hasOwnProperty(prop)) {
obj[prop] = props[prop];
}
}
}