简体   繁体   中英

Using square brackets inside an object: Unexpected Token

I'm leaving out a bunch of context, but I don't think a lot of it is necessary. I have a bunch of code leading up to an object with prop properties. I'm then setting up a $scope.$watch which is watching the object, and then, essentially, broadcasting prop —the name of the property, and newValue[prop] , the value of that property. It looks a bit like this:

$scope.$watch(function(){return object;}, function(newValue, oldValue) {
    for (var prop in object) {
        if (newValue[prop] !== oldValue[prop]) {
            $scope.$broadcast('from-parent', {a: prop, b: newValue[prop]});
        }
    }
};

The broadcasted message console.log() 's out Object {a: (the property's name), b: (the value of the property)} as you would expect.

Strangely though, when I remove out the a: and b: keys, ie

$scope.$broadcast('from-parent', {prop, newValue[prop]});

I get a Uncaught SyntaxError: Unexpected token [ error.

Are you not allowed to refer to properties via brackets in objects? What's going on here?

{prop, newValue[prop]} won't create a property with the name from the prop variable, it just ends up being an invalid object initializer — not because of the [] ( {prop, "foo"} would also have failed), but because object initializers don't work that way.

...the name of the property, and newValue[prop]

To give an object a property name from a variable, in ES5 you have to first create the object, then add the property:

var obj = {};
obj[prop] = newValue[prop];
$scope.$broadcast('from-parent', obj);

In ES6, you'll be able to use the new dynamic property name notation instead:

// REQUIRES ES6!
$scope.$broadcast('from-parent', {[prop]: newValue[prop]});

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