<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script> var inject = { dependencies: {}, register: function (key, value) { this.dependencies[key] = value; }, resolve: function(func, scope) { if (Array.isArray(func)) { var last = func.length - 1; var deps = func.slice(0, last); func = func[last] } else { var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; var fnText = func.toString().replace(STRIP_COMMENTS, ‘‘); var argDecl = fnText.match(FN_ARGS); var deps = argDecl[1].split(‘,‘); } var arr = []; for (var i = 0 ; i < deps.length ; i++) { if (this.dependencies.hasOwnProperty(deps[i])) { arr.push(this.dependencies[deps[i]]) } } return function(){ func.apply(scope || {}, arr); } } // resolve: function (deps, func, scope) { // // var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; // var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; // var fnText = func.toString().replace(STRIP_COMMENTS, ‘‘); // var argDecl = fnText.match(FN_ARGS); // var deps = argDecl[1].split(‘,‘); // deps = deps.map(function(str){ // return str.replace(/\s+/gm,‘‘); // }); // var arr = []; // for (var i = 0; i < deps.length; i++) { // if (this.dependencies.hasOwnProperty(deps[i])) { // arr.push(this.dependencies[deps[i]]) // } // } // return function () { // func.apply(scope || {}, arr); // } // // } // resolve: function (deps, func, scope) { // var arr = []; // for (var i = 0; i < deps.length; i++) { // if (this.dependencies.hasOwnProperty(deps[i])) { // arr.push(this.dependencies[deps[i]]) // } // } // return function () { // func.apply(scope || {}, arr); // } // // } } inject.register(‘$http‘, { ‘getName‘: function () { return (‘$http‘) } }); inject.register(‘$scope‘, { ‘getName‘: function () { return (‘$scope‘) } }); // function MyController($http, $scope) { // console.log($http.getName()); // } function MyController($scope, $http) { console.log($http.getName()); } MyController = inject.resolve([‘$http‘, ‘$scope‘, MyController]); MyController(); </script> </body> </html>
时间: 2024-10-09 18:07:24