代码之家  ›  专栏  ›  技术社区  ›  CaRDiaK

JavaScript-原型

  •  1
  • CaRDiaK  · 技术社区  · 16 年前

    我正在努力获得更好的JavaScript工作知识。所以,我买了Douglas Crockford的《JavaScript的好部分》一书。

    谢谢你的帮助。

    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);
    
    2 回复  |  直到 16 年前
        1
  •  5
  •   Ferdinand Beyer    16 年前

    在指定给object.create的函数表达式末尾缺少右大括号,并且在中没有将object大写 object.create = function(o) {

    //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
    
        2
  •  3
  •   Mark Rushakoff    16 年前

    你似乎错过了这条线的右括号 object.create = function(o) { .... 我看到if语句和 var F = function () {}; ,但不是为 function(o) .

    缺少右大括号确实会抑制输出,因为Javascript会假定(缺少的)右大括号之前的所有内容都是函数定义的一部分,而不是要执行的内容。

    推荐文章