Javascript 如何在不接收语法错误的情况下将this.variable传递给(Angular)JS函数?
这是我的AngulsrJS代码:Javascript 如何在不接收语法错误的情况下将this.variable传递给(Angular)JS函数?,javascript,angularjs,Javascript,Angularjs,这是我的AngulsrJS代码: angular.module("UserApp", ["BaseApp"]) .controller("MainCtrl", ["$http", "$window", "$location", "BaseService", function($http, $window, $location, BaseService) { var self = this; self.username = $location.path().substr($locatio
angular.module("UserApp", ["BaseApp"])
.controller("MainCtrl", ["$http", "$window", "$location", "BaseService", function($http, $window, $location, BaseService) {
var self = this;
self.username = $location.path().substr($location.path().lastIndexOf('/') + 1);
self.watch = function(self.username) {
BaseService.watch(self.username, function() {
// more code
});
};
当我运行这段代码时,我得到一个指向行self.watch=function(self.username){
的错误,错误显示:
Uncaught SyntaxError: Unexpected token .
知道如何将self.username作为参数传递给函数而不出错吗?函数(){
仍将实现您想要的功能(){
仍将实现您想要的功能只需从函数定义中删除属性:
self.watch = function() {
BaseService.watch(self.username, function() {
// more code
});
};只需从函数定义中删除属性:
self.watch = function() {
BaseService.watch(self.username, function() {
// more code
});
}太好了,谢谢!我刚刚意识到,顺便问一下,为什么我的情况下会出现错误?是因为我定义了函数
this.watch
并将this
变量作为参数传递,而参数应该是最终用户决定的变量吗?这是因为参数名不能是引用项取消引用的属性到底意味着什么?因为在我的例子中,我在函数(self.username=$location.path().substr($location.path().lastIndexOf('/')+1);
)之前定义了self.username
,对吗?self.watch(self.username)这可能是您所想的。函数调用不同于函数体,因此具有不同的语法规则引用的是“username”不是独立的,它是通过对包含属性“username”的对象的引用来访问的。太好了,谢谢!顺便问一下,我刚刚意识到,为什么我要在我的例子中出现错误?是因为我定义了函数this.watch
并将this
变量作为参数传递,而参数应该是最终用户决定的变量吗?是因为参数名称不能是取消引用的属性。嗯,取消引用的属性到底意味着什么?因为在我的c例如,我在函数(self.username=$location.path().substr($location.path().lastIndexOf(“/”)+1);
)right?self.watch(self.username)之前定义了self.username
)这可能是您所想的。函数调用不同于函数体,因此具有不同的语法规则引用的是“username”不是独立的,它是通过对包含属性“username”的对象的引用来访问的。太好了,谢谢!顺便问一下,我刚刚意识到,为什么我要在我的例子中出现错误?是因为我定义了this.watch函数并将this变量作为参数传递,而参数应该是最终用户决定的变量吗?您尝试的是使用self.watch
定义属性,名称为self object.Value属性的类型是function(因为这是您在右侧分配的)。谈到函数定义,语法是function(一、二、三)
其中1、2、3是参数的名称,这里不传递值,只定义参数的名称。在您的例子中,您是在函数定义中传递值的。很好,谢谢!我刚刚意识到,顺便问一下,为什么我的例子中会出现错误?是因为我定义了函数吗?注意并传递了一个thi当参数应为最终用户决定的变量时,将s变量作为参数?您所尝试的等同于“var self.username”和self.watch
您在self对象上定义了名为watch的属性。属性值的类型为function(因为这是您在右侧分配的).说到函数定义,语法是function(one,two,three)
其中one,two,three是参数的名称,这里不传递值,只定义参数的名称。在您的例子中,您是在函数定义中传递值。