Monday 2 December 2019

JS Object references && pass by copy && pass by copy and then pass by reference

// Try following on console
// Object pass by references

var a = {test:'hi'}
undefined
var b = a
undefined
{test: "hi"}
{test: "hi"}
b.test = 'hi!'
"hi!"
a
{test: "hi!"}
b
{test: "hi!"}

// Object pass by copy
var test = {test : 'hi'}
undefined
var test2 = {}
undefined
Object.assign(test2,test)
{test: "hi"}
test
{test: "hi"}
test2
{test: "hi"}
test2.test='hihi'
"hihi"
test
{test: "hi"}
test2
{test: "hihi"}

// Object pass by copy and then by reference
var dev = {test: 'hello'}
undefined
var dev2 = {}
undefined
var dev3 = Object.assign(dev2,dev)
undefined
dev
{test: "hello"}
dev2
{test: "hello"}
dev3
{test: "hello"}
dev2.test="helloworld"
"helloworld"
dev
{test: "hello"}
dev2
{test: "helloworld"}
dev3
{test: "helloworld"}

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.

No comments:

Post a Comment