简体   繁体   中英

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 = function(obj) {
    var result = Object.create(this);

    if (obj) {
        for (var key in obj) {
          if(typeof obj[key] == 'function'){
            console.log(result);
            result.protorype[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() {
        return this.username;
    }
});



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

The problem happens when trying to set the property 'getByUsername' passed when defining "a", if you look at the console it will report that:

Uncaught TypeError: Cannot set property 'getByUsername' of undefined 

And the "result" logged has the properties "username" and "password".

PS It will work only in IE > 8

Here is a fiddle http://jsfiddle.net/paglia_s/z62eA/

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

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() {
        return this.username;
    }
});


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM