Javascript OOP,类中的类,得到错误& &不是构造函数& &;,为什么
Javascript OOP, class in class, got error "is not a constructor", why?
我只是在玩一些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
)类,在第一个中使用。
/**
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
相关文章:
- 为什么构造函数不是构造函数
- Javascript:为什么是构造函数's __proto__属性Empty(){}
- 为什么在调用父构造函数时在[]中发送数据
- 为什么我需要为扩展函数设置构造函数
- 为什么"构造函数是一种特殊情况;
- 为什么可以't JavaScript构造函数创建字符串或数字
- 为什么用构造函数创建对象会执行对象's方法
- 为什么在构造函数函数中使用此关键字
- 为什么React在类构造函数中使用setState方法时抛出错误
- 为什么实例构造函数指向最上面的函数构造函数对象
- 为什么这些对象具有不同的构造函数
- 为什么这个私有方法在构造函数中
- 为什么要在构造函数中定义事件处理程序成员函数(内联)以便使用“unbind”
- 为什么 NodeJS 不像浏览器那样执行构造函数
- 为什么更改函数的 .prototype 会影响已使用该构造函数创建的对象的“实例”
- 在ES2015中定义一个类,构造函数方法是什么以及为什么它是必不可少的
- 模拟“类”时,为什么要在 .prototype 属性中设置方法,而不是在构造函数本身中设置方法
- 为什么方法总是添加到原型中,而不是在构造函数中定义
- 为什么这里的构造函数中的“this”总是“Window”对象
- 当你改变原型时,构造函数为什么会改变?(参见代码)