Domanda
Sto cercando di ottenere una migliore conoscenza pratica di JavaScript. Quindi, ho comprato il libro, "JavaScript le parti buone" di Douglas Crockford.
Al momento ho difficoltà a cogliere il prototipo. Tutto sotto sembra funzionare nel mio browser fino a quando non premo // PROTOTYPE Esempio. Qualcuno può darci un'occhiata per capire perché non riesco a ottenere alcun risultato da esso. (La mia pagina ritorna vuota a meno che non commenti tutto il codice prototipo)
Grazie per l'assistenza.
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);
Soluzione
Ti manca una parentesi graffa di chiusura alla fine dell'espressione della funzione assegnata a object.create e inoltre non hai mai usato maiuscole in 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
Altri suggerimenti
Sembra che manchi la parentesi graffa di chiusura per la riga object.create = function (o) {
.... Vedo una parentesi graffa di chiusura per l'istruzione if e per var F = function () {};
, ma non per function (o)
.
Una parentesi graffa di chiusura mancante sopprimerebbe effettivamente l'output, poiché Javascript assumerebbe tutto prima che la parentesi graffa di chiusura (mancante) faccia parte della definizione di una funzione, non qualcosa da eseguire (ancora).