Pregunta

Estoy tratando de obtener un mejor conocimiento práctico de JavaScript. Entonces, he comprado el libro, "JavaScript las partes buenas" por Douglas Crockford.

Tengo dificultades para comprender el prototipo en este momento. Todo lo que aparece a continuación parece funcionar en mi navegador hasta que llegue a // Ejemplo de PROTOTIPO. ¿Puede alguien echarle un vistazo para ver por qué no puedo obtener ningún resultado de él? (Mi página vuelve en blanco a menos que comente todo el código del prototipo)

Gracias por cualquier ayuda.

Barry

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);
¿Fue útil?

Solución

Le falta una llave de cierre al final de la expresión de la función asignada a object.create, y tampoco ha capitalizado Object en 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

Otros consejos

Parece que le falta la llave de cierre para la línea object.create = function (o) { .... Veo una llave de cierre para la instrucción if y para el var F = function () {}; , pero no para function (o) .

Una llave de cierre faltante de hecho suprimiría la salida, porque Javascript asumiría que todo antes de la llave de cierre (faltante) es parte de una definición de función, no es algo que se ejecute (todavía).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top