我正在寻找伪代码答案,或概念性答案。
经过多年的编程,我从未创建过接收函数参数的类方法,这样方法的调用者就可以自动访问“不可见”的属性。
如果我尝试在我的 my_app.controller(...)
方法之外访问 $scope,我会得到一个错误,所以我知道它不是全局的;如果我尝试从 my_app.$scope
或 angular.$scope
访问它,我会得到 undefined。
那么我的函数参数如何访问它:
my_app.controller('my_controller' , function( $scope , ... ) { ... }
更新(我正在学习):
// javascript
var my_class = function( argument_A )
{ this.some_prop = argument_A ;
this.some_method = function( argument_B )
{ console.log( argument_B ) ; // function(boo)
} ;
} ;
var my_instance = new my_class( "my_string" ) ;
var my_function_argument = function( boo ){ } ;
my_instance.some_method( my_function_argument ) ;
最佳答案
函数是一等公民
在 JavaScript 和其他现代语言(Scala、Haskell、LISP 等)中,函数被视为一等公民。具体来说,这意味着该语言支持将函数作为参数传递给其他函数,将它们作为其他函数的值返回,并将它们分配给变量或将它们存储在数据结构中。一些编程语言理论家也需要支持匿名函数(函数文字)。在具有一等函数的语言中,函数的名称没有任何特殊地位;它们被视为具有函数类型的普通变量。 1
上面的例子可以重构为:
var myController = function ($scope, ... ) {
console.log($scope);
$scope.message = "Hello world"
};
my_app.controller('my_controller' , myController );
在这种情况下,.controller
方法将 myController
对象存储在 AngularJS $controllerProvider
服务的缓存中。 IE。 缓存["my_controller"] = myController;
稍后当 $compile
服务遇到需要 Controller 的指令时:
<div ng-controller="my_controller">
{{message}}
</div>
$compile
服务创建一个新的作用域,从 $controller
服务缓存中检索 myController
函数,并使用新范围作为函数的第一个参数。
$compile
服务还创建了一个 $watch
监听函数来跟踪 $scope.message
变量。在每个摘要周期中,如果 $scope.message
已更改,则 DOM 会相应更新。
在问题的例子中:
//These are function invocations, the variable must be defined
console.log( boo ) ; // ERROR: boo is not defined
my_instance.some_method( boo ) ; // ERROR: boo is not defined
最后一种形式使用匿名函数 文字(或函数表达式)。匿名函数是作为参数传递给名为 .some_method
的方法的对象。
//The anonymous function is an object passed as an argument
//boo is a parameter to be supplied when the function is invoked
my_instance.some_method( function( boo ) { } ) ; // NO ERROR
有关函数文字的更多信息,请参阅 MDN JavaScript Reference -- function expression .
依赖注入(inject)和按名称连接参数
通常在 JavaScript 中,函数参数是按位置连接的。在 AngularJS 框架中,函数参数是按名称注入(inject)的。这是怎么做到的?
来自文档:
Inference
In JavaScript calling
toString()
on a function returns the function definition. The definition can then be parsed and the function arguments can be extracted.
-- AngularJS $injector Service API Reference -- Inference
所以在这个例子中:
my_app.controller('my_controller' , function( $scope , ... ) { ... }
$injector
服务对 Controller 构造函数执行 toString()
并解析它。该服务检测到 $scope
是该函数的第一个参数,并使用该知识正确调用该函数。
您可以看到正在使用 fn.toString()
here in the source code .
关于javascript - angular 的 Controller 方法如何使 $scope 可用于我的函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35492239/