2013-02-09 82 views
1

我創建了以下測試,但我不確定它爲什麼不起作用:http://jsfiddle.net/SKphY/。我應該得到三個警告對話框:「你好」,「再見」和「再見」。相反,我只是在前兩個。繼承和對象文字

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 
}); 

的一點是我學習如何與對象繼承工作,在這種情況下,與對象的文字,我很好奇爲什麼它是爲我工作,當我使用jQuery.extend,但不是的Object.create 。從我所知道的情況來看,我似乎遵循了https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create概述的方法。我究竟做錯了什麼?

感謝您的時間, ktm。

回答

3

http://jsfiddle.net/SKphY/1/

作爲@headacheCoder指出的那樣,第二個參數在Object.create爲屬性對象(這也被你鏈接的MDN文檔中描述)。

檢查上面的鏈接爲一個可行的解決方案:

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

Object.create中的第二個參數是屬性對象,不用於合併。改爲使用var obj1 = Object.create(p);,它將按預期工作。

如果指定,而不是未定義,一個對象,其可枚舉自己的屬性(即,沿着它的原型鏈在其自身定義的那些性質,而不是枚舉的屬性)指明屬性描述符被添加到新創建的對象,與相應的屬性名稱。

// 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) } 
}})