Setting Properties in JavaScript Object Which Operator to Use - javascript

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.

Related

JavaScript Function Parameters vs Object Methods

Can someone explain to me the difference of when to use a function by feeding your variables into the parenthesis, and when to tack the function on after the variable with a period, like using the toString() function?
example code
function addMe(a){
a = a+1;
return a;
}
var num = 1;
addMe(num);
num.toString();
I'm not actually sure if my syntax is correct, but I want to know when to feed a variable as a parameter, like how I feed the variable num, to the addMe function. And when to use the function .toString() by putting a period after the variable and typing out the function.
could I have done something like this- provided I built my function correctly?
var num = 1;
num.addMe();
Thanks for the help!
The first is used for simple 'stand alone' functions, while the latter is used for object methods. E.g a number object by default has a toString() method. Some object methods may also require parameters to be passed between the parentheses.
Variables (a function declaration is just a function stored in a variable) are looked up in the scope chain (going up to the next outer scope until a variable with the name is found):
let a = 1; // outer scope
{ // inner scope
console.log(a); // looked up in "inner scope", than "outer scope"
}
Properties of an object are looked up in the objects prototype chain, so if you do
a.b
then a gets looked up in the scopes as explained above, then b is accessed on the resulting object (everything is an object in JavaScript, except for "nothing" (undefined, null)) by looking up the prototype chain. For a simple object, the chain is quite short:
const a = { b: 1 }; // object -> Object.prototype
Here b will be found in the object itself. However all objects inherit from the Object.prototype object, so if you add a property to that (please don't):
Object.prototype.test = 1;
you can then look it up on every object, as the lookup traverses up the prototype chain, and reaches Object.prototype:
console.log({}.test); // 1
Now for numbers (like in your case), they inherit the Number.prototype so you could do:
Number.prototype.addMe = function() {
console.log(this);
};
// two dots are needed to distinguish it from numbers with a fraction (e.g. 1.2)
1..addMe();
That said, now addMe can be called on every number, everywhere in your code. While that might seems useful, it is actually a pain as you don't know where a certain method was added
1..whereDoIComeFrom()
that makes code unreadable and unstructured. Instead if you need a certain functionality multiple times, abstract it into a function, don't touch the native prototypes.
I assume that addMe is just a simplified example, if it isn't, read on:
If you pass an argument to a function in JavaScript, the value will be copied (it is a bit more complicated with non primitives (everything except numbers, booleans etc.)) into the parameter variable of the function called so here:
function addMe(a){
a = a+1;
console.log(a); // 2
return a;
}
var num = 1;
addMe(num);
console.log(num); // 1 ... ?
you actually got two variables (a and num), changing a does not change num. But as you return a you can do:
num = addMe(num);
which copies the value of num into a, then increases a by one and then copues the value of a back to num.
When you did var num = 1 you created a JavaScript object. It looks just like a number but you can think of everything in JavaScript as an object (simplification) and all these objects have different features. So a number has some features, a string has some other features, etc.
You mentioned one feature: toString. Another feature would be toLowerCase.
toString and toLowerCase are functions that come with JavaScript. These functions are then "put on" all of these objects for us to use.
I can have a string variable like
var text = 'MY TEXT'
var lowercaseText = text.toLowerCase()
console.log(lowercaseText) // my text
This code will work because it was decided that the toLowerCase function should work on strings
I can also have an array (list of items)
const list = ['A', 'B', 'C']
const answer = list.toLowerCase()
console.log(answer)
But this code won't work because toLowerCase doesn't work on arrays. So you get the following error message: list.toLowerCase is not a function.
Basically its saying: I don't know what toLowerCase means when used on this list variable (array).
In JavaScript this is called prototypes. Prototype is a way for JavaScript to get some feature from another. Basically: I have all kinds of functions, what object can use what functions. This is called the prototype chain.
In both cases you are using a function. addMe is a function you created and toString is a function in JavaScript that has been placed on objects through this prototype-chain.
Im not actually sure if my syntax is correct
Yes your syntax is correct. Your addMe function is the standard way to create a function in JavaScript.
But i want to know when to feed a variable as a parameter, like how i
feed the variable num, to the addMe function.
Just like you did, you define a function and parameters like you did.
..and when to use the function .toString() by putting a period after
the variable and typing out the function.
When you want to place your function on a object so that all instances of that object can you that object.
In most cases, espcially when you are starting out. You don't have to worry about these prototypes. The way you did.
function addMe(number) {
return number+1
}
const answer = addMe(1) //2
Is a standard way of defining a function and calling it.

Does object literal return a newly created object?

I was learning about object literal syntax {}. I learnt that an object can either be created like
var person = {};
person.name = "myName"
or like
var person = {firstname: "myName"}
Now i wanted to pass this object into a function, and so i learnt that objects can also be created on the fly like
sayHelloTo({firstname: "myName"})
Finally, I typed {} in console, and it showed - `Object().
Does this mean than {} is actually a function or something that is actually returning a newly created object, which then gets stored in the variable? Is it a function or something else? Is it same as var person = new Object() ?
The object literal syntax does create a new object but it is not a function. If anything, it's more akin to an operator.
While the spec does have a whole category of literals (11.8), the object literal is not part of that section. Instead, it's defined later under 12.2.6 (object initializer). As the leading note states:
An object initializer is an expression describing the initialization of an Object, written in a form resembling a literal.
(emphasis mine)

JavaScript constants and object literals

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.

How to access attribute of object as a variable?

I have two objects:
object1={
type: 'obj1',
nName: 'nName'
}
object2={
type: 'obj2',
pName: 'pName'
}
In my js code, I have:
object=GET_OBJECT();
The GET_OBJECT() method returns either object1 or object2, then, I would like to access the object's name attribute which is either nName or pName.
I have one method which will get the name (pName or nName) of the returned object:
function getName(Object, name){
return object.name;
}
where I would like the name to be a variable, so that I can access the pName or nName in this way:
object=GET_OBJECT();
var name='';
if(object.type=='obj1')
name='nName';
else
name='pName';
var finalName=getName(object, name);
But seems it won't work since in:
function getName(Object, name){
return object.name;
}
name is a variable. In JS, is there any way to access attribute as a variable?
Try like this:
function getName(Object, name) {
return Object[name];
}
AS many times before I wonder why people provide solutions and not knowledge. Otherwise the asker will repeat the same mistakes over and over.
The original code uses a function to retrieve an attribute. It is assumed that it is possible to use the parameter to invoke the parameter. In more technical words, Dot notation is being used which must be a valid JavaScript identifier. Tha name after the dot is the pointer the content. Therefore getName always is accessing the attribute name which is likely to be undefined.
The solution shown uses Bracket notation in which uses the content of the parameter (which may not exist) as identifier and then, it resolves the content and this is why it actually works.
Dot notation is faster and easier to read and would be adviced if both are valid options. Bracket notation is to be used when you need resolving in run time. That is what happens when you define setters and getters internally. The following code will use the string passed to ensure (using bracket notation) that whenever you use the identifier by dot notation will call the functions passed.
function myClass(){
//setX and getX should be also defined previous to this
this.__defineSetter__("x",this.setX);
this.__defineGetter__("x",this.getX);
//Object.defineProperty can also be used
};
var tObject = new myClass();
tObject.x = 10; //Getter being called

what does setState: function(){ mean

what does it mean when you set a function like this
setState: function(){
}
The code is incomplete, but it looks like you're assigning a function as the value to a property called setState of an object that isn't shown in your code.
An example:
var myObject = {
prop1: 'abc',
prop2: function() {
alert('def');
}
};
Above, I'm creating a variable called myObject that is an object with two properties, prop1 and prop2. The first one is a string. If I write alert(myObject.prop1) it'll alert "abc".
The second one is a function. If I write myObject.prop2() I'll execute that function, which'll alert "def".
That would appear in the context of an object literal, like this:
var obj = {
setState: function(){
}
};
It assigns the function to the named property of the object. The function is anonymous (it has no name), though the property has a name. You could call the function like so:
obj.setState();
Literal notation is basically a series of propname: value within curly braces ({}), separated by commas, where value can be any valid value —a string, a number, a function reference... The property name can appear literally, as in your example, or in quotes ("propname": value) if the literal name is a reserved word (e.g., you'd need quotes for a property called var since var is a reserved word).

Categories

Resources