我正在创建一个简单的animal.js模块,它在color.js模块中扩展并在app.js中输出。
Animal.js:
var exports = module.exports = {};
exports.animalName = function() {
console.log('Animal Name: Dog');
}
Color.js:我在这里扩展模块animal.js并将其用作Color模块的方法i:e pAnimal();
var animal = require('./animal.js');
exports.animalColor = function() {
console.log('Color is Black');
function pAnimal() {
var pAnimal = animal;
pAnimal.animalName;
}
}
App.js:我在这里尝试从颜色模块中获取值//动物名称:Dog& //颜色是黑色
var localAnimal = require('./color.js');
localAnimal.animalColor();
localAnimal.animalColor.pAnimal();
但是当我在节点服务器中运行它时,我得到这样的错误:
D:\node\module-extend>node app.js
Color is Black
D:\node\module-extend\app.js:4
localAnimal.animalColor.pAnimal();
^
TypeError: localAnimal.animalColor.pAnimal is not a function
at Object.<anonymous> (D:\node\module-extend\app.js:4:25)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
请帮忙。感谢
答案 0 :(得分:0)
以下是有关嵌套函数的一些答案: JavaScript Nested function
pAnimal是一个只能在animalColor范围内调用的函数。
要在外面访问它,你必须这样做:
exports.animalColor = function() {
console.log('Color is Black');
this.pAnimal = function() {
var pAnimal = animal;
pAnimal.animalName();
}
}
然后:
var localAnimal = new require('./color.js');
localAnimal.pAnimal();
答案 1 :(得分:0)
返回Color.js中的函数
{
"types": ["KKYQ", "TGDF", "YHGF"]
}
在app.js中以这种方式调用只需调用以下功能,它将打印Color is Black 动物名称:狗
exports.animalColor = function() {
console.log('Color is Black');
return function pAnimal() {
var pAnimal = animal;
pAnimal.animalName();
}
}
答案 2 :(得分:0)
您需要将函数分配给外部函数的属性以调用它
的像强>
function initValidation()
{
// irrelevant code here
function validate(_block){
console.log( "test", _block );
}
initValidation.validate = validate;
}
initValidation();
initValidation.validate( "hello" );
&#13;
所以试试
exports.animalColor = function() {
console.log('Color is Black');
animalColor.pAnimal=pAnimal;
function pAnimal() {
var pAnimal = animal;
pAnimal.animalName;
}
}