Skip to content Skip to sidebar Skip to footer

Javascript Object.prototype Is Undefined

I'm trying to create a simple extensible 'class' in javascript but when setting property in a prototype it tells that the prototype is undefined: Class = {}; Class.extend = functio

Solution 1:

Just don't create your object by using : Class = {};

But by using : Class = function(){};

Which creates a new object with a prototype..

Your code will look like so :

Class = function(){};

Class.extend = function(obj) {
    var result = Object.create(this);

    if (obj) {
        for (var key in obj) {
          if(typeof obj[key] == 'function'){
            console.log(result);
            result.prototype[key] = obj[key];
          }else{
            result[key] = obj[key];
          };
        };

        result.prototype.constructor = result;
    }

    return result;

}

var a = Class.extend({
    username: "matteo",
    password: "nn te la dico",
    getByUsername: function() {
        returnthis.username;
    }
});


console.log(a, Class.isPrototypeOf(a));​

Solution 2:

You have a typo. result.protorype[key] should be result.prototype[key]

Post a Comment for "Javascript Object.prototype Is Undefined"