Question

I am trying to get a better working knowledge of JavaScript. So, I have bought the book, "JavaScript the good parts" by Douglas Crockford.

I am having difficulty grasping the Prototype at the moment. Everything below seems to work in my browser until I hit //PROTOTYPE Example. Can someone have a look at it to see why I cant get any output from it. (My page returns blank unless I comment all of the prototype code out)

Thank you for any assistance.

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);
Was it helpful?

Solution

You're missing a closing brace at the end of the function expression assigned to object.create, and also you haven't capitalized Object 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

OTHER TIPS

You seem to be missing the closing brace for the line object.create = function(o) {.... I see a closing brace for the if-statement and for the var F = function () {};, but not for function(o).

A missing closing brace would indeed suppress output, because Javascript would assume everything before the (missing) closing brace is part of a function definition, not something to be executed (yet).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top