javascript 传入一个函数(通过引用)作用域中的一个变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26860780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:36:15  来源:igfitidea点击:

Pass in a function (by reference) a variable in the scope

javascripthtmlangularjsangularjs-scope

提问by Joker

There is a way (in angularJS) to pass by reference a variable in the scope in a function (to modify it)? I've tried but the variable change doesn't happen. Here my code

有没有办法(在 angularJS 中)通过引用传递函数作用域中的变量(修改它)?我试过了,但变量变化没有发生。这是我的代码

$scope.modifyVar = function (myVariable){
 myVariable = 92;
}

$scope.modifyVar($scope.txtNumberOfChuck);

回答by V31

You cannot pass a variable by reference in Javascript. However you can pass the complete object and get your values changed.

您不能在 Javascript 中通过引用传递变量。但是,您可以传递完整的对象并更改您的值。

In your case you can pass the $scope object and then modify the property value. Something like this:

在您的情况下,您可以传递 $scope 对象,然后修改属性值。像这样的东西:

$scope.modifyVar = function (myObj){
    myObj.txtNumberOfChuck = 92;
}

$scope.modifyVar($scope);