简体   繁体   中英

Can I create a reference to a variable in javascript?

I tried the following:

    $scope.qs = {};
    $scope.qh = {};
    $scope.qv = {};
    var qs = $scope.qs;
    var qh = $scope.qh;
    var qv = $scope.qv;
    $scope.getQuestionHeaders = function () {
        var url = '/api/Test/GetQuestionHeaders?id=1';
        $http.get(url)
            .success(function (data, status, headers, config) {
               qh = data.testQuestionHeaders;
               qs = qh[0];

My data is assigned to qs and I can see additional fields such as qs.i, qs.q etc. But when I use the chrome developer tools I notice that nothing has been assigned to $scope.qs

That's correct.

You're essentially doing:

foo.someProp = 1;
var bar = foo.someProp;
bar = 3; 

Would you expect foo.someProp to be 3? If you want to update the $scope.qs reference, then you need to do it directly, otherwise you're just changing a local variable reference. You can modify items inside qs:

qs.foo = 1;
console.log($scope.qs.foo);

You are overriding the variables qh and qs , so they loose their previous references. You have to do this if you want to keep both vars synchronized :

$scope.qh = qh = data.testQuestionHeaders;
$scope.qs = qs = qh[0];

Updating properties doesn't affect variables references :

qh.witness = true;
$scope.qh.witness === qh.witness === true; // true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM