Setting and getting a boolean object property in JavaScript
So I just submitted my very first pull request on a collaborative software project (a web app built with Ember.js), and I noticed that I had carelessly included a boolean variable (conditionally set inside a function) in an object literal using only the variable name rather than a key-value pair, like so:
function fruitStand () {
// do something here to decide if this basket is pretty, and if not..
var prettyBasket = false;
var myObj = {
apples : 1,
oranges : 2,
prettyBasket
};
return myObj;
}
I was surprised that accessing the boolean later with
var stand = fruitStand();
var truthy = stand.prettyBasket;
seems to work, but is this valid JavaScript? Otherwise poor form? Setting it with something like prettyBasket : prettyBasket
feels less DRY if the above is OK.
You are unintentionally utilizing a feature of ES6, specifically shorthand object literal notation, which you can read more about here.
Also, depending on whether or not the application you are working on is built with Ember-cli (and is using an ES6 transpiler) or you are building a regular Ember application (potentially without transpilation), you should be cognizant that only the latest browsers will support that code unless it is being transpiled to standard object literal notation.
链接地址: http://www.djcxy.com/p/86436.html上一篇: Perl 6和打印列