Javascript OOP,类中的类,得到错误& &不是构造函数& &;,为什么

Javascript OOP, class in class, got error "is not a constructor", why?

本文关键字:构造函数 为什么 OOP Javascript 错误      更新时间:2023-09-26

我只是在玩一些javascript OOP,只是为了好玩,但我得到一个错误…

我试图在一个类中创建类,不知道是否可能。

有人能给我指路吗?

看到我的问题在这里: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不是构造函数"

希望这是有意义的!

主要问题是您没有从第一个闭包返回一个函数。但除此之外,你在这里要做的还有很多问题。这是一个比较传统的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.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);
        };
    };
    this.__init__();

你也有一个问题,你分配给这个没有绑定到适当的作用域在你的第二个init函数。可以这样修改:

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

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

您的问题是您没有正确使用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