This question already has answers here:
How does this object method definition work without the "function" keyword?
(2 answers)
Closed 6 years ago.
I entered this expression in the Firefox and Chrome Dev Console and I wonder why it is valid JavaScript:
var x = { a (b) {} };
console.log(x);
x is then set to an object with the property "a" containing a function called "a" with an argument identifier "b".
How is this valid JavaScript syntax? The colon is missing after "a" and I do not understand the function definition.
This is ES6 / ES2015 syntactic sugar (Property shorthand).
With ES6:
const obj = {
a(b) {
// Shorthand method
// `this` context is `obj`
},
c
};
is equal to
var obj = {
a: function a(b) {
},
c: c
};
In JavaScript, when you write:
var x = { a (b) {} };
It will consider it as:
var x = {
a: function (b) {
}
}
For example, you can check this and it will clear your doubt:
var x = { a (b) { console.info('function called') } };
x.a();
This will call the function which is assigned to property a of object x.
Related
This question already has answers here:
What does the 'in' keyword in javascript mean?
(3 answers)
Closed 1 year ago.
Ok so I have seen the in keyword in many different codes but i have never understood what they do.
Here is an example
let duck = new Bird() // Bird is a constructor i made. Not important
function in keyword() {
let ownProps = [];
for (let property in duck) {
if(duck.hasOwnProperty(property)) {
ownProps.push(property);
}
}
}
Sooo, what does it do?
Please explain it to me
The in operator tests if the string on the left side of the operator is a property name in the object on the right side.
let obj = { a: 1 };
console.log("a" in obj); // true
console.log("b" in obj); // false
The in keyword also plays a role in the for ... in loop, which iterates through the properties (the enumerable properties) of an object:
let obj = { a: 1, b: 2 };
for (let x in obj) {
console.log(x);
}
That will log "a" and "b", because those are the enumerable properties of the object.
This question already has answers here:
JavaScript object functions and `this` when unbound and returned in expression/parens
(2 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 4 years ago.
Here is an example where o.foo(); is 3 but (p.foo = o.foo)(); is 2?
function foo() {
console.log( this.a );
}
var a = 2;
var o = { a: 3, foo: foo };
var p = { a: 4 };
o.foo(); // 3
(p.foo = o.foo)(); // 2”
If I do something like this then I get 4 which is what I want. How are those 2 examples are different?
p.foo = o.foo;
p.foo(); // 4
This :
(p.foo = o.foo)();
Is pretty much the same as doing this:
d = (p.foo = o.foo);
d();
Basically what it says is that the return of an assignment is the function itself in the global context. On which a is 2.
actually your code is wrong because your snippet doesnt run, you should be doing the following: console.log( this.a );
and now, lets see how this works.
function foo() {
console.log( this.a );
}
this will call this in the scope of the caller, so lets investigate our results.
so, you are setting a=2 globally, and then in the objects o.a = 3 and p.a=4
so:
calling o.foo it will return 3 because this is pointing to o
calling p.foo it will return 4 because this is pointing to p
BUT
calling (p.foo = o.foo)(); it will return 2 because it is not pointing to any object, so it will take your scope (which is the global scope) and then it will return 2.
if you go with:
p.foo = o.foo
p.foo() //4
it will return 4 successfully because it is pointing to p.
Performing that assignment operation before the function call here:
(p.foo = o.foo)();
causes the object reference to p to be lost. If you instead wrote
p.foo = o.foo;
p.foo();
you'd get 4. As it is, you get 2 because the value of this will be window in the function.
Because that parenthesized subexpression is an assignment result, there's no object lookup directly associated with the result of the expression — the value of the assignment expression is just the function reference without a contextual object. Thus the runtime doesn't have a value to use for this when it calls the function, so this is bound by default to window (or the global object in whatever context).
This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 5 years ago.
I've noticed things like this work:
let x = { a: 1 };
function reassignProperty(obj, key, newValue) {
obj[key] = newValue;
}
reassignProperty(x, "a", "hello");
console.log(x.a); //prints hello
But this doesn't:
function reassignObject(obj) {
obj = { a: "some new value" };
}
reassignObject(x);
console.log(x.a); //still prints hello
It seems you can reassign properties of an object (pointers within an object), even if the values are reference types themselves. i.e. we could do things like reassignProperty(x, "a", { inner: 55 }), and it will still be the same outside the function scope. But reassigning the reference to the object itself doesn't?
I've seen people argue javascript passes variables into functions by value, but not by reference. Why then does it seem to able to reassign the properties inside the object, and have access to the changes outside the function scope? This doesn't seem to me to be strictly "pass by value"
In the second case use dot notation instead of object literal
let x = {
a: 1
};
function reassignObject(obj) {
console.log("Passed from function call ", obj);
if (obj.hasOwnProperty('a')) {
obj.a = "some new value"
}
console.log("After reassinging value ", obj)
}
reassignObject(x);
console.log(x.a);
This question already has answers here:
Getters \ setters for dummies
(14 answers)
Closed 5 years ago.
my so far understanding with object literal is we can use it like the key value pair, where key is the property and the value can be a actual value, a function or a anonymous function
function a() {
return 'value b';
}
var result = {
'keya': 'valueA',
'keyb': a,
'keyc': function () {
console.log('some value');
}
};
till i read this block of code
var obj = {
log: ['test'],
get latest() {
if (this.log.length == 0) return undefined;
return this.log[this.log.length - 1];
}
}
console.log(obj.latest); // Will return "test".
my question is, in the above code the function latest() doesnt have any key then how can it be used inside a object literal, am i missing something
This is ES6 (which is also called ES2015) syntax, it's a newer version of Javascript that lets you do this.
You would've had to have the key there in ES5 code.
This question already has answers here:
dynamic keys for object literals in Javascript [duplicate]
(8 answers)
How do I interpolate a variable as a key in a JavaScript object?
(6 answers)
Closed 9 years ago.
In JavaScript, is there a shorter way to create object from a variable then below.
var d = 'something';
function map(d){
var obj = {};
obj[d] = d;
return obj;
}
well, the shortest looks like, but it is wrong as key is literal d than its value.
function wrong(d){
return {d:d}
}
I don't mind the first version, but wonder any succinct way.
thanks.
I recommend instantiating an anonymous function.
function map(d) {
return new function () {
this[d] = d;
};
}
Using an anonymous function will allow you to keep all of your property declarations in the same place to be more organized. If you need other default keys set you can add them easily:
new function () {
this[d] = d;
this.foo = 'bar';
};
Versus with an object literal you'll have declarations in two places:
obj = {
foo: 'bar'
};
obj[d] = d;
That all said, the original code is fine as-is. It's concise, readable, and maintainable.
function map(d) {
var obj = {};
obj[d] = d;
return obj;
}