2013-02-09 80 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) } 
}})