jeudi 30 avril 2015

Extending prototype on object literal

If I have the following code, why does it return an error saying Cannot set property 'second_prop' of undefined . I thought that you can extend the prototype property and add more variables and methods to the object prototype. Since the two console statements return 'Object' and true, then why does it return an error of undefined. My thinking is, if the 'obj' is an object of type Object, then I should be able to do temp.prototype.newproperty? So then the Object will have a 'newproperty'. But I'm obviously wrong, so there's something I am missing here. Even more, why do I need to do Object.create() when the obj is already an object literal? Isn't it already an object? I'm just looking at some examples and trying to understand this

    var obj = {
        first_property: 'first property'
    }
    console.log(typeof obj);
    console.log(obj instanceof Object);

    var temp = Object.create(obj);
    temp.prototype.second_prop = 'second property'

Output

//object
//true
//Uncaught TypeError: Cannot set property 'second_prop' of undefined

So, why can't i do temp.prototype or obj.prototype?




Aucun commentaire:

Enregistrer un commentaire