Javascript 在模块JS节点中创建对象及其实例
我不熟悉Node和JS,尝试实现一个模块。在我的模块中,我希望有一个对象,我可以在模块的其他方法中初始化它的实例(特别是在我的例子中,它是一个响应对象)。 所以我的代码是:Javascript 在模块JS节点中创建对象及其实例,javascript,node.js,Javascript,Node.js,我不熟悉Node和JS,尝试实现一个模块。在我的模块中,我希望有一个对象,我可以在模块的其他方法中初始化它的实例(特别是在我的例子中,它是一个响应对象)。 所以我的代码是: exports.myModule = { //response object Response: function() { // some initializing and functions function testFunction(){ console.log("test functi
exports.myModule = {
//response object
Response: function()
{
// some initializing and functions
function testFunction(){
console.log("test function inside object was called");
}
}
//now i am trying to create an instance
tester: function() {
var res = new Response();
res.testFunction();
}
}
然而,我得到语法错误,我不明白
(这段代码没有意义,因为我还在测试模块中对象的基本创建
已编辑
现在,当创建新响应时,我得到错误:
ReferenceError:未定义响应请尝试以下操作
var Foo = {
//response object
Response: function()
{
// some initializing and functions
function testFunction(){
console.log("test function inside object was called");
}
}
//now i am trying to create an instance
tester: function() {
var res = new Foo.Response();
res.testFunction();
}
}
module.exports = Foo;
首先,这有很大的问题。比如Response
方法很奇怪。但是我不想太多地编辑你原来的代码片段
就像我在评论中提到的一样,有更好的方法可以做到这一点,即使你修复了那些明显的错误,我建议你在这里搜索一下节点教程
编辑:如果有人发现自己在这里,请在完成一些一般背景知识工作后参考OP提供的答案
工作示例可能类似于:
module.exports = {
//response object
Response: function()
{
// some initializing and functions
this.testFunction = function (){
console.log("test function inside object was called");
}
},
//now i am trying to create an instance
tester: function() {
var res = new this.Response();
res.testFunction();
}
};
我最终解决了这个问题,将对象声明放在模块之外,如下所示:
function Response(){
// some initializing and functions
function testFunction(){
console.log("test function inside object was called");
}
}
var Foo = {
//now i am trying to create an instance
tester: function() {
var res = new Foo.Response();
res.testFunction();
}
}
问题在于上下文。当您执行新响应时,它会在全局空间中查找它,而该函数未定义。因此,为了访问该函数,请像我一样使用this.Response,或者像我一样使用Foo.Response
让我们来看一看dat error yo!主要是因为我在您提供的代码段中看到了语法问题^^请查看编辑@TheDembinski,我正要回答您在响应中出错:function()您不能引用
响应之类的内容。您可以执行类似的操作:module.exports={…}
然后引用该模块。老实说,这很花哨。我会提供答案,看看你是否喜欢它。Hanks,现在我得到了信息:ReferenceError:Foo没有定义。我在谷歌上搜索,就是找不到这种情况,可能是因为我没有用最好的方式来做。请确保你查找所有内容!如果你如果有此线程,请继续删除它或接受答案。出现错误;function testFunction(){
应该是this.testFunction=function(){
我接受你的答案,因为你的答案更具教育意义,尽管我的答案更方便。随着时间的推移,我会理解这个主题的正确设计模式。谢谢你的帮助!@ChrisG-这绝对是一个可能的选择。我不想/不知道如何用提供的代码片段解决所有问题。我想我最好是轻轻地向正确的方向暗示。
module.exports = {
//response object
Response: function()
{
// some initializing and functions
this.testFunction = function (){
console.log("test function inside object was called");
}
},
//now i am trying to create an instance
tester: function() {
var res = new this.Response();
res.testFunction();
}
};