如何访问JavaScript中所需函数之外的唯一注入依赖项值
以下是场景: 我想将依赖项注入到由第三方库执行的回调函数中。这很简单,因为我可以将回调封装在一个闭包中——但问题源于这样一个事实,即我还希望能够在需要它的函数之外使用该依赖项的任何修改属性 我举个例子。首先,示例用例: 在Express.js中动态构造app.[verb]调用-用户手动设置[verb]属性,如下所示: ItemController.js:如何访问JavaScript中所需函数之外的唯一注入依赖项值,javascript,dependency-injection,Javascript,Dependency Injection,以下是场景: 我想将依赖项注入到由第三方库执行的回调函数中。这很简单,因为我可以将回调封装在一个闭包中——但问题源于这样一个事实,即我还希望能够在需要它的函数之外使用该依赖项的任何修改属性 我举个例子。首先,示例用例: 在Express.js中动态构造app.[verb]调用-用户手动设置[verb]属性,如下所示: ItemController.js: exports.create = function(req, res, $scope) { $scope.method = 'post';
exports.create = function(req, res, $scope) {
$scope.method = 'post';
$scope.path = 'item/create';
res.send('Creates a new item');
};
假设我有一个injector对象,带有一个process方法,该方法以数组的形式返回函数所需的依赖项:
injector.process = function(fn) {
// RegExp constant matching code comments
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,
// convert the function to a string and strip any comments out
fnString = fn.toString().replace(STRIP_COMMENTS, ''),
// find the opening and closing parentheses of the function
openParenIndex = fnString.indexOf('('),
closeParenIndex = fnString.indexOf(')'),
// slice the content between the parens to their own string
contents = fnString.slice(openParenIndex + 1, closeParenIndex),
// convert contents to an array, split by comma or whitespace
args = contents.match(/([^\s,]+)/g);
// if the function expects no arguments, we need to specify an empty array
if (args === null) { args = []; }
// return an array of the expected arguments
return args;
}
我如何确保itemController.js的每个方法都获得它自己唯一的$scope实例,并且app[verb]调用被动态构造成这样的东西
app.post('/item/create', function(req, res) {
res.send('Creates a new item');
});
尝试在这样的对象中创建函数
var app = {
post : function() {
alert('posted');
},
get : function() {
alert('got');
}
}
然后你可以调用这样的函数。假设动词有函数名
app[verb](); //if verb = "post" it will alert "posted"
我希望这正是您想要的。尝试在这样的对象中创建函数
var app = {
post : function() {
alert('posted');
},
get : function() {
alert('got');
}
}
然后你可以调用这样的函数。假设动词有函数名
app[verb](); //if verb = "post" it will alert "posted"
我希望这就是您想要的。使用evalapp.+verb+这不会带来安全问题吗?正如人们所说,eval是邪恶的……是的,它会的。请参阅下面我的更好答案。使用evalapp.+动词+这不会带来安全问题吗?正如人们所说,eval是邪恶的……是的,它会的。请看下面我更好的答案。不幸的是,这并不能真正回答实际问题。但是,由于你不厌其烦地花时间回答问题,我对你的答案投了赞成票。后来我放弃了这个想法,在这里写了一篇关于它的博文:不幸的是,这并不能真正回答实际问题。但是,由于你不厌其烦地花时间回答问题,我对你的答案投了赞成票。后来我放弃了这个想法,在这里写了一篇关于它的博客: