简体   繁体   中英

Using object literal notation to set a property's value in terms of another property

I encounter an error in the following code because of the way I try to define the 'scanning' property on my reader object.

app.controller("turingController", ["$scope", function($scope) {



    $scope.cellArray = []; 

    for( var i=0; i<=999; i++) {

        $scope.cellArray[i] = {

            index: i,

            content: "B",

        };

    };


    $scope.reader = {

        location: 500,

        state: "q1",

        scanning: $scope.cellArray[$scope.reader.location].content
    };

}]);

But if I don't use object literal notation to define the 'scanning' property, it works fine. Like this:

$scope.reader = {

    location: 500,

    state: "q1",

    };

$scope.reader.scanning = $scope.cellArray[$scope.reader.location].content

I realize that I've solved the problem, but I'm still wondering why it doesn't work in the first code? Thanks in advance!

When you are defining $scope.reader in the first example, you are also calling $scope.reader (actually $scope.reader.location ) within the definition. At the point you call $scope.reader.location you have not finished defining $scope.reader . So it gets confused...

In the second method, you first define the $scope.reader object, then add a new property ( scanning ) to it, setting the value based in part on $scope.reader . This is fine since the $scope.reader object now exists

At the point in which you construct the object literal for $scope.reader , you haven't actually defined $scope.reader yet — you're trying to reference a variable that does not exist yet.

However, by setting it afterwards, in your new code, $scope.reader has been set, so you can reference it without any issues.

This is javascript problem, not really angularjs. location doesn't exist until the following line $scope.reader = {}; is finished.

It is something along this line:

var A = 100;
var B = A = B; 

//What is the value of B? 
//Does (B = A) execute first, so B = 100? 
//Does (A = B) execute first, so B = undefined?

//answer, B is undefined.

//this is analogy to your case
// var R.A = 100 never happens until R = {} is finished.
// so B = A is undefined
var R = {
  A: 100,
  B: A
};

The expression is evaluated prior to assignment. You statement is like this:

var temp = {
    location: 500,
    state: "q1",
    scanning: $scope.cellArray[$scope.reader.location].content
};
$scope.reader = temp;

So when the property is being assigned a value, $scope.reader has not yet been set.

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