I know I can do this in JavaScript:
RequestDate: {
'0' : 'previous_activity_date',
'1': 'next_activity_date'
}
And I can do this:
this.RequestDate = {};
this.RequestDate[App.FORWARD] = 'next_activity_date';
this.RequestDate[App.BACK] = 'previous_activity_date';
Is there a way of making the following work:
RequestDate: {
App.Back : 'previous_activity_date',
App.Forward: 'next_activity_date'
},
The above obviously errors, is there a way to make it work?
you can do this.
RequestDate: {
[App.Back]: 'previous_activity_date',
[App.Forward]: 'next_activity_date'
}
Short answer: no. You can only have literal keys in the object literal. Your own solution is the best one if you want to use constants.
http://bclary.com/2004/11/07/
11.1.5 Object Initialiser
An object initialiser is an expression describing the initialisation of an Object, written in a form resembling a literal. It is a list of zero or more pairs of property names and associated values, enclosed in curly braces. The values need not be literals; they are evaluated each time the object initialiser is evaluated.
As you have noticed, you can write this:
RequestDate = {};
RequestDate[App.Back] = 'previous_activity_date';
RequestDate[App.Forward] = 'next_activity_date';
But the javascript syntax does not allow an expression before the : of the JSON notation.
Related
This question already has answers here:
What do square brackets around a property name in an object literal mean?
(2 answers)
Closed 5 years ago.
I just started JS, wondering why there are [] around Symbol. For example: in an object.
var bow = {
[Symbol('apple')] : something,
[Symbol('banana')] : something,
....
}
Also, when it comes to iterator:
var iterableObject = {
[Symbol.iterator] : function() {.....}
}
Can anyone explain what is the use of these [] around them? I googled a while but didn't find satisfied answer, thank you in advance.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
The bracket notation is just another way of accessing a property on an object. In particular, it's used when the property name is not valid for use with the dot notation, such as Symbol.iterator.
You may also want to look at computed property names: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names
These are similar but are instead used to set properties when an object is defined rather than get properties from an already defined object.
The square brakets are just part of object literal syntax.
When you make an object using object literal syntax it is now possible to use variables to set the keys inside the object.
const string = 'whatever'
const normalObject = {
[string]: 'something else'
}
This results in normalObject having one property, 'whatever' pointing to 'something else'
// normalObject
{ whatever: 'something else' }
The use of brackets in object literal syntax is just to allow you to use a variable to set the key in an object.
bringing this back to your example this is just allowing you to use Symbols as keys in your object.
You may have noticed that this is a little weird. Up until very recently an object could only have String keys. Symbols are not the other thing you can use as keys in an object.
var bow = {
[Symbol('banana')] : something,
[Symbol('banana')] : something,
....
}
this will result in an object with two different Symbol(banana) pointing to something.
I'm confused by the = vs. : when assigning a value to a property in an object
Now I know that there are a couple ways to create an object:
Object Literal
Object Constructor
With an object Literal you would use ":" to assign a value to a property:
var myObject = {firstName: "John", lastName="Smith" };
There we are using ":" to set the value to the property.
I also know a function itself is an object. And you can probably expose public properties from there as part of the function being an object?
So is it if you're assigning a function to a property that you'd use "="? I am assuming yet but what about something like this:
var phantom = require('phantom');
var World = function World(callback) {
phantom.create("--web-security=no", "--ignore-ssl-errors=yes", { port: 12345 }, function (ph) {
var phantomProcess = ph;
createBrowserPage = function(){
phantomProcess.createPage(function(page) {
this.headlessPage = page;
})
};
});
callback();
};
module.exports.World = World;
I assume I have this right in that I want to expose createBrowserPage through exports. I wouldn't use createBrowserPage: and use a ":" instead of "=" to assign that anonymous function to the createBrowserPage property right?
= is used for assignment in a Javascript statement as in:
variable = "foo";
: is used in an object literal declaration between a property name: value as in:
var obj = {
prop1: value1,
prop2: value2
};
If you want to expose your createBrowserPage() function through exports, you have several options, some of which involve creating an object and some of which involve assigning a property to an object. Which you choose and how you declare it leads to whether you use : or =. It depends upon which way you choose to write the javascript code that exposes createBrowserPage(). There is no single answer there. I will offer you a couple options.
If, in one statement, you want to assign one new property to the exports object, then you would use = like this:
module.exports.myFunc1 = myLocalFunction1;
If, in one statement, you wish to assign all your exported functions, then you would assign an object that was assigned with =, but used : in the declaration of the object like this:
module.exports = {
myFunc1: myLocalFunction1,
myfunc2: myLocalFunction2
};
In the first example, you are adding one new property to the exports object and assigning that property a value.
In the second example, you are declaring a new Javascript literal object (which uses prop: value syntax to declare its properties. And, then you are assigning that whole object to module.exports which actually replaces the entire existing exports object with a new one and this new object has two properties on it.
Your question is a bit confusing, but if you're interested in the precise meaning and grammar of : and = it's like this:
The colon (:) symbol is not an operator, it is part of the litteral object notation syntax and separates property names (a litteral string or simple identifier) from their value (any expression). Colons are only used in that context and as part of the trinary conditional operator (?:).
Something in curly brackets is parsed as a litteral object if and only if the { is not the first character in the instruction (otherwise it defines a block) and does not follow a function expression or declaration.
The assignment operator (=) (spec) is a binary operator, it can be used in any expression as long as its left operand is a valid left-hand-side expression, and it returns the value of the right operand. Unless strict mode is used, it will silently fail to assign a value to read-only properties.
Maybe is just a stupid question, but,
I would appreciate having an explanation of the following behavior:
var obj = {
key : "val1",
123 : "val2"
};
obj.key; // "val1"
obj.123; // Syntax error: missing; before statement
obj[123]; // "val2"
Why obj.key is different from obj.123
although they have been declared both as keys of obj.
Accessing the object literal in this way obj.123 is wrong.
And declaring the object in the following way is correct?
The browsers I have tested are IE9, firefox and chrome and for all of them it works fine.
var obj = {
123 : "val1"
};
JavaScript will let you use just about any string as an object property name, but when accessing properties with the dot notation you're only supposed to use property names that would be valid JS identifiers - which have to start with a letter, the underscore or a dollar sign. So for property names that don't meet the rules for valid identifiers you have to access them with the bracket notation.
Although the bracket notation works with a number, behind the scenes JS will convert that number to a string.
In JS terminology how do you name this kind of object:
var a = {"a":"wohoo", 2:"hello2", "d":"hello"};
I believe it is not an array as 'length' property is undefined on it.
Then what is it?
thanks
It's just a normal object.
The initializer is called an object literal.
It's just an object, i.e. an instance of Object. Same as doing:
var a = new Object();
a.a = "wohoo";
a["2"] = "hello2";
a.d = "hello";
It is an object.
In Chrome:
>> ({"0": 1}).toString()
"[object Object"]
According to Mozilla, it is an object literal:
An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.
It is an object (and it work like a hash).
You could go to http://javascript.crockford.com/ for more deep info on javascript.
Its called as a literal notation. Its very powerful stuff dear and has almost replaced old XML in the field. In below example two notations are used both are having same purpose.
var userObject = {
name : 'user1',
age: 24,
run:function(destination){
//make the man run
} };
var userObject = {}; userObject.name =
"user1"; userObject.age = 24;
userObject.run =
function(destination){
//make this man to run };
So now out there its new hot topic whether AJAX (Asynchronous JavaScript & XML) to AJ (Asynchronous JavaScript). Jokes apart its new stuff called as JSON. check below stuff for better understanding this thing.
http://en.wikipedia.org/wiki/JSON
http://msdn.microsoft.com/en-us/library/bb299886.aspx
var a="1";
b={a:a},
the b variant isn't {"1":1},why will this happened?
also want to know if i want to get the result what i want ,how can i solve this problem
JavaScript has a syntax quirk where the bit on the left-hand side of the : in an object literal isn't an expression like the bit on the right-hand side.
It can be either a quoted string literal, or an identifier token. In the case of an identifier, the token is taken verbatim, as if it were a quoted string. So {a:"1"} is the same as {"a":"1"}.
If you want to use an expression as a property name, you have to do so using the [] property access operator:
var b= {};
b[a]= a;
because b is assigned to an object literal that has an 'a' property with the value of whatever is in the a var, which is 'i'. This is how javascript works when defining object literals
var x = { prop : value }
even if you defined a var prop before you assign x, 'prop' is the literally (pun intended) a key in the object literal.
Also, i think you wanted
var b = {a:a};
The first a in your javascript object is a literal; it will not be treated as a variable and evaluated.