2009-10-27 71 views
1

我想要获得更好的JavaScript工作知识。所以,我购买了Douglas Crockford的书“JavaScript是好的部分”。JavaScript - 原型

我现在在抓住Prototype时遇到困难。下面的一切似乎都在我的浏览器中工作,直到我点击// PROTOTYPE示例。有人可以看看它,看看为什么我不能从它得到任何输出。 (我的页面返回空白,除非我评论所有的原型代码)

谢谢你的任何帮助。

巴里

var stooge = { 
    "first-name": "Jerome", 
    "last-name": "Howard", 
    "nickname": "J", 
    "profession" : 'Actor' 
}; 

// below is augmenting 
var st = stooge; 
st.nickname = "curly"; 
// st.nickname and nick are the same because both are ref's to the same object 
var nick = st.nickname; 


document.writeln(stooge['first-name']); //expect Jerome -- this is "suffix" retrieval 
document.writeln(st.nickname); //expect "curly" -- this is "notation" retrieval 
document.writeln(nick); //expect "curly" 
document.writeln(stooge.profession); 


//PROTOTYPE EXAMPLE; 
if (typeof Object.create !== 'function') 
{ 
    object.create = function(o) { 
      var F = function() {}; 
      F.prototype = o; 
      return new F(); 
}; 
var another_stooge = Object.create(stooge); 
another_stooge['first-name'] = 'Barry'; 
document.writeln(another_stooge['first-name']); 
// the below should be inherited from the prototype therefore "Actor" 
document.writeln(another_stooge.profession); 

回答

5

您在分配给object.create的函数表达式末尾缺少一个右大括号,并且您还没有在object.create = function(o) {中大写Object。

//PROTOTYPE EXAMPLE; 
if (typeof Object.create !== 'function') 
{ 
    Object.create = function(o) { // <--- "Object" instead of "object" 
     var F = function() {}; 
     F.prototype = o; 
     return new F(); 
    }; 
} // <--- Closing brace was missing 
+0

谢谢Tim,我现在不会再被抓住了:) – CaRDiaK 2009-10-27 11:34:02

+0

@费迪南德:很好的编辑,谢谢 – 2009-10-27 11:43:50

3

你似乎缺少行object.create = function(o) {结束花....我看到一个右括号的if语句,为var F = function() {};,而不是function(o)

一个缺失的右大括号确实会抑制输出,因为在(缺失的)大括号是功能定义的一部分之前,Javascript会假定所有东西,而不是要执行的东西(还)。

+0

谢谢你。这两个答案完全解决我的问题。我会将Tim标记为答案,因为他有更少的分数,并且还指出了O的大小写,但非常感谢你Mark你帮助我理解:) – CaRDiaK 2009-10-27 11:33:31