JavaScript - Prototype
-
06-07-2019 - |
Pergunta
Eu estou tentando obter um melhor conhecimento de trabalho de JavaScript. Então, eu comprei o livro, "JavaScript as partes boas" por Douglas Crockford.
Estou tendo dificuldade em entender o Prototype no momento. Tudo abaixo parece funcionar no meu navegador até que eu bati // PROTÓTIPO Exemplo. Alguém pode ter um olhar para ele para ver por que eu não posso obter qualquer saída dele. (Minha página retornos em branco a menos que eu comentar toda a fora código de protótipo)
Obrigado por qualquer ajuda.
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);
Solução
Você está faltando uma chave de fechamento no final da expressão função atribuída a object.create, e também você não tem capitalizado objeto em 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
Outras dicas
Você parece estar faltando a chave de fechamento para o object.create = function(o) {
linha .... Vejo uma chave de fechamento para a declaração if-e para o var F = function () {};
, mas não para function(o)
.
A falta chave de fechamento seria saída fato suprimir, porque o Javascript assumiria tudo antes da cinta (falta) de fechamento é parte de uma definição de função, e não algo a ser executado (ainda).