Set value to a referenced JavaScript object - javascript

For example, I have the following JS object:
var obj = {
n: 0,
o: {}
};
var nGlobal = obj.n;
var oGlobal = obj.o;
And want to use global variables in order to make it look like this:
var obj = {
n: 5,
o: {
x: 7
}
};
Obviously, I am able to assign a value to a property of oGlobal:
oGlobal.x = 7;
However, is there any way to change the value of obj.n through nGlobal, without mentioning obj?
Just something like this:
console.log(obj); // {n: 1, o: {}}
nGlobal.set(5);
// or
nGlobal.value = 5;
console.log(obj); // {n: 5, o: {}}

Short answer:
No, there is not.
Long answer:
In JS primitive types are immutable and passed by values.
JS implements pass-by-value strategy, which means that ALL data is always passed by value (in case if you pass a reference to object - the reference is passed by value)
One important consequence from the items above: in JS there is no way to change the original object using the = operation. That is: you can modify an object when you have a reference to it, but you cannot swap one object with something else so that all other references also "were modified".
Related:
Evaluation strategy - Call by sharing
Credits:
Felix Kling

Related

Modifying variables that are passed by reference in Javascript

I was watching a JavaScript talk, and the tutor said that if we pass a property of an object in a function it will actually change the real value, because we will be passing the variable by reference. Here is the slide:
but when I tried to practice the concept, that wasn't the case. Here is my code:
var obj = {val: 5};
function changeVal(x) {
x = x+5;
return x;
}
console.log(obj.val) // 5
console.log(changeVal(obj.val)) // 10
console.log(obj.val) // 5
I was expecting obj.val to change to 10.
Please tell me what's wrong here, and correct me if I am wrong. Thanks
You are passing not the object, but the primitive type. So when you pass the val of the obj, it is a number and is a primitive type.It copies the val and passes the copy to the object.
If you pass like this, it will work
var obj = {val: 5};
function changeVal( param ) {
param.val = param.val + 5;
return param.val ;
}
console.log(obj.val) // 5
console.log(changeVal(obj)) // 10
console.log(obj.val) // 10
You are not actually passing an object, just passing the value of property(val).
If you will pass obj in changeVal(), then it will actually change the value of the property of passed object.
For that you need to do like:
var obj = {val: 5};
function changeVal(x)
{
x = x+5;
return x;
}
console.log(obj.val); // 5
changeVal(obj); // Need to pass object instead of value of the property's value
console.log(obj.val); // 10
Primitive types (string, integer, boolean, etc...) are immutable, which means if you change one of the values inside a function, the callee (scope which calls your function) will not see the change.
function doSomething(a) {
a = a + 1;
}
var value = 2;
console.log(value); // result: 2
doSomething(value);
console.log(value); // result: 2
Pass-by-reference only works for objects. Like this:
function doSomething(obj) {
obj.attribute = obj.attribute + 1;
}
var myObject = {attribute: 2};
console.log(myObject.attribute); // result: 2
doSomething(myObject);
console.log(myObject.attribute); // result: 3
More reading about Javascript types:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
Say for instance you have an Iphone . Now lets say a manufacturing company calls you and asks to borrow your Iphone for a reference just so they can design an Iphone that is similar and sell it to customers . Your original Iphone still exists and is never gone , but every now and then the factory needs to use it for a reference , think of your function as the factory that just make a copy of obj.
//Original data
var obj = {val: 5};
Once your function returns something , it technically becomes a value
Example :
return 3; is a value of 3
so
function changeVal(x) {
x = x+5;
return x;
}
is a new value of x which in this case would be x + 5;
x is a copy of whatever you pass into the function .
Hope this helps.

Difference between Object.assign and just assign

I would like to know the difference between this:
Object.assign(otherObject, {
someNewProperty: ''
});
and
otherObject.someNewProperty = '';
And.. which one is faster?
Thanks.
The Object.assign() method is used to copy the values of all
enumerable own properties from one or more source objects to a target
object. It will return the target object.
Whereas otherObject.someNewProperty = ''; is a method to directly assign a value to some property of an object.
Obviously the Object.assign pattern is much slower : jsperf.com/assign-vs-equals
For single property, direct assignment (otherObject.someNewProperty = '') is twice faster, but for multiple values - time will grow. Each property + 5% to 10%. Also, code-wise Object.assign is nicer for multiple options.
Object.assign(otherObject, {
prop1: '',
prop2: '',
prop3: '',
...
});
VS
otherObject.prop1 = '';
otherObject.prop2 = '';
otherObject.prop3 = '';
...
You simply can run Profiles tab in Chrome Development tool and run few tests.
Object.assign() is a pretty versatile function that is designed to do complex object composition.
The property dot notation is a straight forward way to assign a single value to a single property.
Regarding which is faster, that's irrelevant considering these are not equivalent, and as one of my all time favorite posts noted "asking which one runs faster is maybe a non-starter".
There is another important thing to show here about the differences between assign directly and using Object.assign(actually, not exactly a difference, but a important thing to be aware).
If you have a Object that's assigned to another variable in JS, like this:
const a = { a: 1 }
const b = a
then, you decided to use Object.assign to change the value in a and assign to another variable(d), you will change the value in b as well(even you not assigning the Object.assign return to a, in this example let's assign to a new variable d).
const d = Object.assign(a, { a: 2 })
console.log(a) // { a: 2 }
console.log(b) // { a: 2 }
console.log(d) // { a: 2 }
Basically, it's important to know that Object.assign will mutate the target object as well all variables pointing to it.
Now, if you use directly the assignment to d, it'll not change the value in a(and in b as well will not change).
const d = { ...a, ...{ a: 2 }}
console.log(a) // { a: 1 }
console.log(b) // { a: 1 }
console.log(d) // { a: 2 }
This is actually a good question:
We just found a bug, where we would assign properties to a file using Object.assign.
const file = new File(["foo"], "foo.txt", {
type: "text/plain",
});
file.name='test'; // does not update the readonly value but doesn't return an error
Object.assign(file,{name:'test'}); // error: 'Cannot set property name of #<File> which has only a getter'

using key value pair of same object inside itself with 'this' in javascript

Let's say I have two objects like
var a = {
b: 1,
c: this.b
};
And
var funcObj = {
b : function() {
return 1;
},
c: function() {
console.log(return this.b())
}
}
On logging these two like
console.log(a.c)//results undefined
console.log(funcObj.c()) //results 1
Why can't the first function use the this property but the second one can?
I am really confused.
The answer depends on what this refers to in each context. In JavaScript, this is bound to whatever object was on the left of the dot (.) when the current function was called. If we're not in a function, things get a little hairier -- this is either the global window object or undefined, depending on the environment.
In your first example, the value of this is dependent on the surrounding context. As JavaScript builds your object a, it evaluates this.b. Whatever object this is currently bound to has no b property, so the c property is set to undefined.
In your second example, when you call funcObj.c() the this in the function gets bound to funcObj. So, when you ask for the b property, you get the b you defined above. The fact that funcObj.b is a function is actually irrelevant. The following would work just as well:
var funcObj = {
b : 1,
c: function() {
console.log(return this.b)
}
}
You cannot refer to other properties in the declaration as part of a Javascript literal declaration. So, in your Javascript literal declaration:
var a = {
b: 1,
c: this.b
};
this is not set to what you want and a has not yet been initialized yet so you can't refer to it either. There is simply no way to reach the other properties at the time of the literal declaration. This is a limitation of the current specification for Javascript. You could do this instead:
var a = {
b: 1
};
a.c = a.b;
because a is fully formed at that point so you can then reference other properties in it.
Or, in modern browsers, you could even use a getter to get the "live" version of b like this (which isn't exactly the same functionality as you were asking for since it's a "live" version of b that will track it's value), but shows you another possibility:
var a = {
b: 1,
get c() {
return b;
}
};
console.log(a.c); //results 1
In your second example:
var funcObj = {
b : function() {
return 1;
},
c: function() {
console.log(return this.b())
}
}
console.log(funcObj.c()) //results 1
You are calling funcObj.c() and that will set the value of this inside of c to funcObj so thus you can reference other properties via this.
The main difference here is that this is not set to the object inside of Javascript literal definition (your first example), but this is set to the object when you invoke a method as in funcObj.c().
I know this post is a bit old, but I came across it while trying to figure out how to solve a similar issue.
I was wanting to do something like:
const x = {
a: 12,
b: a + 1
}
console.log(x) //results undefined
(That's extremely simplified compared to what I was actually doing, but the principle is the same.)
My solution was to first create a function that would build the object I wanted, then pass in the primary value I was trying to act on (in this example, the value in 'a'):
function buildObj (val) {
const response = {
a: val,
b: val + 1
};
return response;
}
And then:
const x = buildObj(12)
console.log(x) // results { a: 12, b: 13 }
Once x has been initialized, any subsequent attempt to access
x.a
or
x.b
will return the values stored therein.
If a future searcher comes across this question because they're wanting to take an action on a value stored in a nested key within the same object, hopefully this will help.

Is there a way to provide named parameters in a function call in JavaScript?

I find the named parameters feature in C# quite useful in some cases.
calculateBMI(70, height: 175);
What can I use if I want this in JavaScript?
What I don’t want is this:
myFunction({ param1: 70, param2: 175 });
function myFunction(params){
// Check if params is an object
// Check if the parameters I need are non-null
// Blah blah
}
That approach I’ve already used. Is there another way?
I’m okay using any library to do this.
ES2015 and later
In ES2015, parameter destructuring can be used to simulate named parameters. It would require the caller to pass an object, but you can avoid all of the checks inside the function if you also use default parameters:
myFunction({ param1 : 70, param2 : 175});
function myFunction({param1, param2}={}){
// ...function body...
}
// Or with defaults,
function myFunc({
name = 'Default user',
age = 'N/A'
}={}) {
// ...function body...
}
ES5
There is a way to come close to what you want, but it is based on the output of Function.prototype.toString [ES5], which is implementation dependent to some degree, so it might not be cross-browser compatible.
The idea is to parse the parameter names from the string representation of the function so that you can associate the properties of an object with the corresponding parameter.
A function call could then look like
func(a, b, {someArg: ..., someOtherArg: ...});
where a and b are positional arguments and the last argument is an object with named arguments.
For example:
var parameterfy = (function() {
var pattern = /function[^(]*\(([^)]*)\)/;
return function(func) {
// fails horribly for parameterless functions ;)
var args = func.toString().match(pattern)[1].split(/,\s*/);
return function() {
var named_params = arguments[arguments.length - 1];
if (typeof named_params === 'object') {
var params = [].slice.call(arguments, 0, -1);
if (params.length < args.length) {
for (var i = params.length, l = args.length; i < l; i++) {
params.push(named_params[args[i]]);
}
return func.apply(this, params);
}
}
return func.apply(null, arguments);
};
};
}());
Which you would use as:
var foo = parameterfy(function(a, b, c) {
console.log('a is ' + a, ' | b is ' + b, ' | c is ' + c);
});
foo(1, 2, 3); // a is 1 | b is 2 | c is 3
foo(1, {b:2, c:3}); // a is 1 | b is 2 | c is 3
foo(1, {c:3}); // a is 1 | b is undefined | c is 3
foo({a: 1, c:3}); // a is 1 | b is undefined | c is 3
DEMO
There are some drawbacks to this approach (you have been warned!):
If the last argument is an object, it is treated as a "named argument objects"
You will always get as many arguments as you defined in the function, but some of them might have the value undefined (that's different from having no value at all). That means you cannot use arguments.length to test how many arguments have been passed.
Instead of having a function creating the wrapper, you could also have a function which accepts a function and various values as arguments, such as
call(func, a, b, {posArg: ... });
or even extend Function.prototype so that you could do:
foo.execute(a, b, {posArg: ...});
No - the object approach is JavaScript's answer to this. There is no problem with this provided your function expects an object rather than separate params.
Lots of people say to just use the "Pass an object" trick so that you have named parameters.
/**
* My Function
*
* #param {Object} arg1 Named arguments
*/
function myFunc(arg1) { }
myFunc({ param1 : 70, param2 : 175});
And that works great, except... when it comes to most IDEs out there, a lot of us developers rely on type / argument hints within our IDE. I personally use PhpStorm (along with other JetBrains IDEs, like PyCharm for Python and AppCode for Objective-C).
And the biggest problem with using the "Pass an object" trick is that when you are calling the function, the IDE gives you a single type hint and that's it... How are we supposed to know what parameters and types should go into the arg1 object?
So... the "Pass an object" trick doesn't work for me... It actually causes more headaches with having to look at each function's docblock before I know what parameters the function expects.... Sure, it's great for when you are maintaining existing code, but it's horrible for writing new code.
Well, this is the technique I use... Now, there may be some issues with it, and some developers may tell me I'm doing it wrong, and I have an open mind when it comes to these things... I am always willing to look at better ways of accomplishing a task... So, if there is an issue with this technique, then comments are welcome.
/**
* My Function
*
* #param {string} arg1 Argument 1
* #param {string} arg2 Argument 2
*/
function myFunc(arg1, arg2) { }
var arg1, arg2;
myFunc(arg1='Param1', arg2='Param2');
This way, I have the best of both worlds. New code is easy to write as my IDE gives me all the proper argument hints. And, while maintaining code later on, I can see at a glance, not only the value passed to the function, but also the name of the argument. The only overhead I see is declaring your argument names as local variables to keep from polluting the global namespace. Sure, it's a bit of extra typing, but it's trivial compared to the time it takes to look up docblocks while writing new code or maintaining existing code.
Update - 2022
JavaScript now has the ability to have something close to named parameters using object destructuring available in ES6. Most newer browsers can use this feature See browser support
This is how it works:
// Define your function like this
function myFunc({arg1, arg2, arg3}) {
// Function body
}
// Call your function like this
myFunc({arg1: "value1", arg2: "value2", arg3: "value3"})
// You can also have default values for arguments
function myFunc2({firstName, lastName, age = 21}) {
// Function body
}
// And you can call it with or without an "age" argument
myFunc({firstName: "John", lastName: "Doe"}) // Age will be 21
myFunc({firstName: "Jane", lastName: "Doe", age: 22})
The best part is that most IDE's now support this syntax and you get good argument hint support
TypeScript
For those of you using TypeScript, you can do the same thing using this syntax
function myFunc(
{firstName, lastName, age = 21}:
{firstName: string, lastName: string, age?: number}
) {
// Function body
}
OR, using an interface
interface Params {
firstName: string
lastName: string
age?: number
}
function myFunc({firstName, lastName, age = 21}: Params) {
// Function body
}
If you want to make it clear what each of the parameters are, rather than just calling
someFunction(70, 115);
do the following:
var width = 70, height = 115;
someFunction(width, height);
Sure, it's an extra line of code, but it wins on readability.
Another way would be to use attributes of a suitable object, e.g. like so:
function plus(a,b) { return a+b; };
Plus = { a: function(x) { return { b: function(y) { return plus(x,y) }}},
b: function(y) { return { a: function(x) { return plus(x,y) }}}};
sum = Plus.a(3).b(5);
Of course for this made up example it is somewhat meaningless. But in cases where the function looks like
do_something(some_connection_handle, some_context_parameter, some_value)
it might be more useful. It also could be combined with "parameterfy" idea to create such an object out of an existing function in a generic way. That is for each parameter it would create a member that can evaluate to a partial evaluated version of the function.
This idea is of course related to Schönfinkeling aka Currying.
Calling function f with named parameters passed as the object
o = {height: 1, width: 5, ...}
is basically calling its composition f(...g(o)) where I am using the spread syntax and g is a "binding" map connecting the object values with their parameter positions.
The binding map is precisely the missing ingredient, that can be represented by the array of its keys:
// map 'height' to the first and 'width' to the second param
binding = ['height', 'width']
// take binding and arg object and return aray of args
withNamed = (bnd, o) => bnd.map(param => o[param])
// call f with named args via binding
f(...withNamed(binding, {hight: 1, width: 5}))
Note the three decoupled ingredients: the function, the object with named arguments and the binding. This decoupling allows for a lot of flexibility to use this construct, where the binding can be arbitrarily customized in function's definition and arbitrarily extended at the function call time.
For instance, you may want to abbreviate height and width as h and w inside your function's definition, to make it shorter and cleaner, while you still want to call it with full names for clarity:
// use short params
f = (h, w) => ...
// modify f to be called with named args
ff = o => f(...withNamed(['height', 'width'], o))
// now call with real more descriptive names
ff({height: 1, width: 5})
This flexibility is also more useful for functional programming, where functions can be arbitrarily transformed with their original param names getting lost.
There is another way. If you're passing an object by reference, that object's properties will appear in the function's local scope. I know this works for Safari (haven't checked other browsers) and I don't know if this feature has a name, but the below example illustrates its use.
Although in practice I don't think that this offers any functional value beyond the technique you're already using, it's a little cleaner semantically. And it still requires passing a object reference or an object literal.
function sum({ a:a, b:b}) {
console.log(a+'+'+b);
if(a==undefined) a=0;
if(b==undefined) b=0;
return (a+b);
}
// will work (returns 9 and 3 respectively)
console.log(sum({a:4,b:5}));
console.log(sum({a:3}));
// will not work (returns 0)
console.log(sum(4,5));
console.log(sum(4));
Coming from Python this bugged me. I wrote a simple wrapper/Proxy for node that will accept both positional and keyword objects.
https://github.com/vinces1979/node-def/blob/master/README.md
NB. My answer of 2016 is not correct and misleading as mentioned in comments.
Trying Node-6.4.0 ( process.versions.v8 = '5.0.71.60') and Node Chakracore-v7.0.0-pre8 and then Chrome-52 (V8=5.2.361.49), I've noticed that named parameters are almost implemented, but that order has still precedence. I can't find what the ECMA standard says.
>function f(a=1, b=2){ console.log(`a=${a} + b=${b} = ${a+b}`) }
> f()
a=1 + b=2 = 3
> f(a=5)
a=5 + b=2 = 7
> f(a=7, b=10)
a=7 + b=10 = 17
But order is required!! Is it the standard behaviour?
> f(b=10)
a=10 + b=2 = 12
This is admittedly pseudocode, but I believe it'll work (I know it works in TypeScript; I'm adopting it for JavaScript).
// Target Function
const myFunc = (a=1,b=2,c=3) => {a+b+c}
// Goal usage:
myFunc(a=5, b=6) // 14
myFunc(c=0) // 3
// Set your defaults
const myFuncDefaults = {a:1, b:2, c:3};
// Override them with passed parameters
const myFuncParams = (params) => { return Object.assign(myFuncDefaults, params)}
// Use the overloaded dict as the input
const myFunc2 = (params) => {
let {a, b, c} = myFuncParams(params);
return myFunc(a, b, c)
}
// Usage:
myFunc({a:5, b:6}) // 14
myFunc({c:0}) // 3
// Written more succinctly:
const myFunc = (params) => {
let {a,b,c} = Object.assign({a:1, b:2, c:3}, params)
return a + b + c
}
For what it's worth, TypeScript makes this kind of nice with hinting:
interface IParams {
a: number;
b: number;
c: number;
}
const myFunc = (params: Partial<IParams>): number => {
const default: IParams = {a:1, b:2, c:3};
let {a, b, c} = Object.assign(default, params)
return a + b + c
}
Yes, well, kind of. I've found two solutions. I'll explain just one.
In this solution, we give up positional arguments, though.
We can use an object (almost identical to a dict in Python) to pass the arguments.
In this example, I'm using the function to generate the name of a image file:
// First we define our function with just ONE argument
function name_of_img(img_desc){
// With this step, any undefined value will be assigned a value
if(img_desc.size == undefined) {img_desc.size = "400x500"}
if(img_desc.format == undefined) {img_desc.format = ".png"}
console.log(img_desc.size + img_desc.format)
}
// Notice inside our function we're passing a dict/object
name_of_img({size: "200x250", format : ".jpg"})
// In Python name_of_img(size="200x250" , format="jpg")
// returns "200x250.jpg"
name_of_img({size: "1200x950"})
// In Python name_of_img(size="1200x950")
// returns "1200x950.png"
We can modify this example, so we can use positional arguments too, we can also modify it so non valid arguments can be passed, I think I will make a GitHub repository about this.
Contrary to what is commonly believed, named parameters can be implemented in standard, old-school JavaScript (for boolean parameters only) by means of a simple, neat coding convention, as shown below.
function f(p1=true, p2=false) {
...
}
f(!!"p1"==false, !!"p2"==true); // call f(p1=false, p2=true)
Caveats:
Ordering of arguments must be preserved - but the pattern is still useful, since it makes it obvious which actual argument is meant for which formal parameter without having to grep for the function signature or use an IDE.
This only works for booleans. However, I'm sure a similar pattern could be developed for other types using JavaScript's unique type coercion semantics.

__hash__ for javascript?

Is there a way to give objects in js custom hashes, just as overriding
__hash__()
in python let's someone define how a given object is hashed into a dictionary.
My underlying question is: what hash function is used to put js objects into associative arrays, and can I over-ride it?
You mean using objects as keys, how do you make sure you access that key again?
The magic method is toString(). Turns out all objects in JS use string keys, and the toString() method is called if it's not a string.
http://jsfiddle.net/udsdT/1/
var objA = {
data: 'yay',
toString: function() {
return 'value_as_key';
}
};
var objB = {
data: 'some other totally data thing',
toString: function() {
return 'value_as_key';
}
}
var foo = {};
foo[objA] = 'abc';
foo[objB] = 'def';
foo['value_as_key'] = 'qwe';
foo.value_as_key = 'omg';
foo[objA]; // 'omg'
foo[objB]; // 'omg'
foo['value_as_key']; // 'omg'
foo.value_as_key; // 'omg'
​​​​​​Usually though, you really don't want to use whole objects as keys. Especially if you dont create your own toString() method, since the default toString() method on basic objects isn't exactly very awesome...
({a:123}).toString() // [object Object]
({b:456}).toString() // [object Object]
var foo = {};
foo[{a:123}] = 'wtf';
foo[{asdf:9876}]; // 'wtf'
foo['[object Object]']; // 'wtf
In JS, you can't control the hashing, but you don't have to.
Two things are the same if they're equal. The hash is not part of the definition, it's just an implementation detail. Under the covers, two different objects may have the same hash, but they're still different, and the implementation has to deal with that magically (e.g., by using a chaining hash table).
Also, the keys of an object are always strings—the interpreter will stringify the values inside the hash constructor, inside the [], or after the ., rather than storing the actual values, which means that this rarely comes up in the first place.
To give some examples:
function X() {}
x = new X()
y = new Y()
h = {x: 2, y: 3} // h has 2 members, named "x" and "y"
a = (x, y)
b = (x, y)
h[a] = 4
h[b] = 5 // h has 3 members, named "x", "y", and "[object Object]"
Put in Python terms, it's as if dict called __repr__ on keys instead of __hash__ (although this isn't quite 100% accurate), which means you can provide a custom toString method to control equal-ness of different instances of your class.

Categories

Resources