Commas in Javascript - javascript

<script>
(function() {
$('html').addClass('js');
var contactForm = {
container: $('#contact'), <-- THIS COMMA
init: function() {
$('<button></button>', {
text: 'Contact Me'
})
.insertAfter('article:first')
.on('click', this.show);
}, <---------------------------------- AND THIS COMMA
show: function() {
contactForm.container.show();
}
};
contactForm.init();
})();
</script>
In the above script, I noticed:
container: $('#contact'),
Is that one way to declare a variable? Doing the following breaks the script:
var container = $('#contact');
Also, what is with the commas after the init function and the container variable (if it is a variable)?

This way you declare an object:
var contactForm = {
// properties:
property1 : value,
property2 : value,
property3 : value,
// methods:
method1 : function() {
// ...
},
method2 : function() {
// ...
}
};
You can find more information about JavaScript objects in MDN ...and in the comments below :)

That block of code (beginning with var contactForm = {) is declaring an object using object literal notation. Commas separate the different key-value pairs in the object literal notation.
var obj = { key1: value1, key2: value2 };

Commas are used to separate name/value pairs when defining objects:
var newObj = {
name: value,
another_name: another_value
};

That is called Object literal notation.
Which is basically a Comma-Separated list of name/value pairs, wrapped in curly braces.
Advantage of this notation is that all data within the braces are encapsulated and not defined globally which avoids conflicts with other scripts or libraries.

Those are key:value pairs of the object contactForm you defined separated by commans
var obj = { key1 : value1,
key2 : value2
method1 : function(){
// definition
},
method2 : function(){
// definition
}
}
The thing that confused me in my early days is that what is function(){....} doing inside a variable(in this case an object) definition until I discovered functions are objects too in js which may not be the same case in language you have used earlier .
and this function function(){....} without name is called a anonymous function.
Here's a good thread on anonymous function Why do you need to invoke an anonymous function on the same line?

Related

Difference between ES6 object method assignment: a, 'a', and ['a']?

With ES6, I can create a new object with functions like the following:
var obj = {
something() {}
};
That makes sense. But I can also do this:
var obj = {
'something'() {}
};
Or I can do this:
var obj = {
['something']() {}
};
Is there a difference between these three syntaxes? Why are all of these syntactically valid?
Is there a difference between these three syntaxes?
Not wrt to the results in your example.
However, the different syntaxes do have different characteristics. The way the property name is defined is not specific to method definitions btw, the rules apply to all property names:
Property names that are valid identifier names or number literals don't need to be quoted:
{
foo: ...,
10e4: ...,
if: ...,
}
Anything else needs to be quoted:
{
'foo+bar': ...,
'abc def': ...,
'123,45': ...,
}
The square bracket syntax is new in ES6 and allows you do dynamically compute property names:
{
[getPropertyName()]: ...,
['item' + (i * 3)]: ...,
}
Why are all of these syntactically valid?
Because the grammar allows it:
MethodDefinition :
PropertyName ( StrictFormalParameters ) { FunctionBody }
GeneratorMethod
get PropertyName ( ) { FunctionBody }
set PropertyName( PropertySetParameterList ) { FunctionBody }
PropertyName :
LiteralPropertyName
ComputedPropertyName
LiteralPropertyName :
IdentifierName
StringLiteral
NumericLiteral
ComputedPropertyName :
[ AssignmentExpression ]
(not sure what kind of answer you expect here)
If you consider methods to be equivalent to assigning a function to the property, it seems to make sense to apply the same rules for property names to function/method names.
First and second are the same, and do the same as
obj.something = function something() {}
the third one creates an anonymous function and stores it in obj.something. It's an equivalent to this:
obj['something'] = function() {}
Quotes allow to create keys (and hence function names) that are not valid identifiers in JS, for example:
var obj = {
'123'() {}
};
creates a function with the name 123, believe it or not.
The square brackets syntax allows arbitrary expressions, so you can do
var obj = {
['myfunc_' + getFuncName()] () {}
}
and similar cool things.

Jquery & javascript - function result, as property name

I'd like to get an input name, as a property name, using jquery.
The html
<input name="data[First][Second]" />
The script
$.post(
'/url',
{
$("input").prop("name"): $("input").val()
}
);
how can it be done (directly)?
You can't use a variable value as a property name in a literal. You have to do it in two steps and to use the bracket notation :
var obj = {};
obj[$("input").prop("name")] = $("input").val();
$.post('/url', obj);
If you don't want to break the flow and you want an expression, you can use a function expression :
$.post(
'/url', (function(){
var obj = {};
obj[$("input").prop("name")] = $("input").val();
return obj;
})()
);
A very slight advantage is also that you don't pollute the external scope with a new variable, but it's usually not clearer.

How to refer to class using variable

If I have this object:
var myclass = {
foo: {
bar: function(var) {}
},
some: {
bar: function(var) {}
}
}
and I want to call the bar function depending on a variable that defines the parent level of the object like this:
var part = "some";
myclass.part.bar(var);
How can I do?
You can do it using array access notation:
myclass[part].bar(var);
JavaScript objects are like associative arrays, and you can use a property name to either set or get the property's value, you can even create new properties with this syntax.
For example:
var obj = { a : 1 };
console.log(obj["a"]); // 1
obj["b"] = 2; // this creates a property called b and assigns 2 as the value
console.log(obj["b"]); // 2
You can keep a reference to a function as a variable, which is a little cleaner than a string.
var func = myclass.foo.bar;//or myclass.some.bar
...
func.call(myclass, var);
Or keep a reference to the part:
var part = myclass.foo;//or myclass.some
part.bar.call(myclass, var);

Access a predefined child object from its parent object with a string

I have a javascript object that has been returned from a Database.
I want to build a function that, if passed a parent object and a string, can return a child from the parent with the same name as the string.
the following code obviously does not work, but gives the idea:
function filter (object, text) {
return object.Text
}
such that
var object = {
"prop1": 1,
"prop2":
{
"ChildProp1": 1,
"ChildProp2": 2,
}
}
var text = "prop2"
var ChildObject = filter(object, text)
//expected content of ChildObject = {
// "ChildProp1": 1,
// "ChildProp2": 2,
// }
You don’t need a function to access a property by name; it’s a fundamental part of JavaScript’s syntax.
object[text]
Try using this:
function filter(object, text) {
return object[text];
}
This allows you to dynamically access a property with bracket notation, instead of statically accessing one with dot notation.
Just use array syntax,
Object["property"]

Curly braces inside JavaScript arguments for functions

What do the curly braces surrounding JavaScript arguments for functions do?
var port = chrome.extension.connect({name: "testing"});
port.postMessage({found: (count != undefined)});
A second possible answer has arisen since this question was asked. Javascript ES6 introduced Destructuring Assignment.
var x = function({ foo }) {
console.log(foo)
}
var y = {
bar: "hello",
foo: "Good bye"
}
x(y)
Result: "Good bye"
The curly braces denote an object literal. It is a way of sending key/value pairs of data.
So this:
var obj = {name: "testing"};
Is used like this to access the data.
obj.name; // gives you "testing"
You can give the object several comma separated key/value pairs, as long as the keys are unique.
var obj = {name: "testing",
another: "some other value",
"a-key": "needed quotes because of the hyphen"
};
You can also use square brackets to access the properties of the object.
This would be required in the case of the "a-key".
obj["a-key"] // gives you "needed quotes because of the hyphen"
Using the square brackets, you can access a value using a property name stored in a variable.
var some_variable = "name";
obj[ some_variable ] // gives you "testing"
Curly braces in javascript are used as shorthand to create objects. For example:
// Create an object with a key "name" initialized to the value "testing"
var test = { name : "testing" };
alert(test.name); // alerts "testing"
Check out Douglas Crockford's JavaScript Survey for more detail.
var x = {title: 'the title'};
defines an object literal that has properties on it. you can do
x.title
which will evaluate to 'the title;
this is a common technique for passing configurations to methods, which is what is going on here.

Categories