I have created the following test and I am unsure why it does not work: http://jsfiddle.net/SKphY/. I should be getting three alert dialogs: “hello” and “goodbye” and “goodbye”. Instead I am only geting the first two.
var p = {
hello : function() {
alert('hello');
}
};
var obj1 = Object.create(p, {
goodbye : function() {
alert('goodbye');
}
});
var obj2 = $.extend(p, {
goodbye : function() {
alert('goodbye');
}
});
$(function() {
// The third line (below) gives the parser error:
// 'Uncaught TypeError: Property 'goodbye' of object #<Object>
// is not a function'
obj1.hello();
obj2.goodbye(); // This executes fine
obj1.goodbye(); // This gives the parser error
});
The point is I am learning how to work with object inheritance, in this case with object literals, and I am curious why it is working for me when I use jQuery.extend, but not with Object.create. From what I can tell, I seem to have followed the approach that is outlined at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create. What am I doing wrong?
Thanks for your time,
ktm.
http://jsfiddle.net/SKphY/1/
As @headacheCoder points out, the second argument in
Object.createis for properties object (this is also described in the MDN document you linked).Check the link above for a workable solution: