簡體   English   中英

Javascript Object.prototype未定義

[英]Javascript Object.prototype is undefined

我正在嘗試在javascript中創建一個簡單的可擴展“類”,但是當在原型中設置屬性時,它告訴原型是未定義的:

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));​

當在定義“a”時嘗試設置屬性'getByUsername'時會發生問題,如果你看控制台,它會報告:

Uncaught TypeError: Cannot set property 'getByUsername' of undefined 

並且記錄的“結果”具有“用戶名”和“密碼”屬性。

PS它只能在IE> 8中使用

這是一個小提琴http://jsfiddle.net/paglia_s/z62eA/

你有一個錯字。 result.protorype[key]應該是result.prototype[key]

只是不要使用以下方法創建對象:Class = {};

但是通過使用:Class = function(){};

這會創建一個帶有原型的新對象..

您的代碼將如下所示:

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));​

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM