簡體   English   中英

Javascript OOP,類中的類,出現錯誤“不是構造函數”,為什么?

[英]Javascript OOP, class in class, got error “is not a constructor”, why?

我只是在玩som javascript OOP,只是為了好玩,但出現錯誤...

我正在嘗試通過class創建類,並且不知道這是否可行。

誰能以正確的方式讓我...

在這里看到我的問題: http : //jsfiddle.net/wBZ4r/2/

function MyClass() {
    var server;

this.__init__ = function() {
    this.server = new this.Server();
    console.log(this.server.url);
}();

/* -------- Server Class ------------------ */
this.Server = function() {
    var url;
    this.__init__ = function() {
        this.url = "server/test.json";
    }();

    this.connect = function() {
        console.log(this.url);
    };
};
}(window.myclass = new MyClass());

收到此錯誤:“ this.Server不是構造函數”

希望有道理!

調用時未定義this.server 因此它被讀為undefined並失敗。

將代碼更改為此可以使其成功創建對象:

 this.__init__ = function() {
        this.server = new this.Server();
        console.log(this.server.url);
    };

    /* -------- Server Class ------------------ */
    this.Server = function() {
        var url;
        this.__init__ = function() {
            this.url = "server/test.json";
        }();

        this.connect = function() {
            console.log(this.url);
        };
    };
    this.__init__();

您還遇到了一個問題,即您在未將其綁定到第二個init函數中的適當范圍的情況下分配給它。 可以這樣解決:

var url,self = this;
this.__init__ = function() {
self.url = "server/test.json";
}();

工作提琴: http : //jsfiddle.net/wBZ4r/4/

主要問題是您沒有從第一個閉包中返回函數。 除此之外,您在此處嘗試執行的操作還有很多問題。 這是Class的更傳統風格的示例。 在示例中,我在第一個實例中實例化了第二個( Server )類。

http://jsfiddle.net/wBZ4r/5/

/**
closure to prevent others from accessing
*/
(function() {
/** 
Server class
*/
function Server() {
    this.url = "/some/url";
}

/**
Server prototype, defines connect function
*/
Server.prototype = {
    connect: function() {
        console.log(this.url);
    }
}

/**
MyClass
*/
function MyClass() {
    /**
    MyClass instansiates a new Server
    */
    this.server = new Server();
};

var thing = new MyClass();
thing.server.connect();
})();

您的問題是您沒有正確使用this關鍵字。 我建議您閱讀Javascript Garden ,學習很多有關JS的知識非常好。

function MyClass() {
    var self = this;
    /* -------- Server Class ------------------ */
    function Server() {
        var selfServer = this;
        this.__init__ = function () {
            selfServer.url = "server/test.json";
        }();

        this.connect = function () {
            console.log(selfServer.url);
        };
    };
    this.__init__ = function () {
        self.server = new Server();
        console.log(self.server.url);
    }();
    this.Server = Server;
}(window.myclass = new MyClass());

JSFiddle

暫無
暫無

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

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