简体   繁体   中英

Inheritance and Object Literals

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.create is for properties object (this is also described in the MDN document you linked).

Check the link above for a workable solution:

var obj1 = Object.create(p, {
    goodbye : {value : function() {
        alert('goodbye');
    }}
}); 

The second argument in Object.create is for a properties object, not for merging. Use var obj1 = Object.create(p); instead and it will work as expected.

If specified and not undefined, an object whose enumerable own properties (that is, those properties defined upon itself and not enumerable properties along its prototype chain) specify property descriptors to be added to the newly-created object, with the corresponding property names.

// Example where we create an object with a couple of sample properties.
// (Note that the second parameter maps keys to *property descriptors*.)
o = Object.create(Object.prototype, {
// foo is a regular "value property"
foo: { writable:true, configurable:true, value: "hello" },
// bar is a getter-and-setter (accessor) property
bar: {
    configurable: false,
    get: function() { return 10 },
    set: function(value) { console.log("Setting `o.bar` to", value) }
}})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM