After Update and show In console cartype Safari but inside car object Fiat Expected Output inside car object Safari
I dont want to use car.type = Safari in update function because i used //cartype inside multiple objects.
var cartype = 'Fiat';
var car = {type:cartype, model:"500", color:"white"};
function update(){
cartype = 'Safari';
}
function show(){
console.log(cartype);
document.getElementById("demo").innerHTML = car.type;
}
<p id="demo"></p>
<button id="upd" onclick="update();">Update</button>
<button id="shw" onclick="show();">show</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
It seems that your only hope is to set car.type
to Safari.
var cartype = 'Fiat';
var car = {type:cartype, model:"500", color:"white"};
function update(){
cartype = 'Safari';
car.type = cartype;
}
function show(){
console.log(cartype);
document.getElementById("demo").innerHTML = car.type;
}
<p id="demo"></p>
<button id="upd" onclick="update();">Update</button>
<button id="shw" onclick="show();">show</button>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can use a getter function to get the global cartype from car.type
.
var cartype = 'Fiat';
var car = {get type(){return cartype;}, model:"500", color:"white"};
function update(){
cartype = 'Safari';
}
function show(){
console.log(cartype);
document.getElementById("demo").innerHTML = car.type;
}
<p id="demo"></p>
<button id="upd" onclick="update();">Update</button>
<button id="shw" onclick="show();">show</button>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Learn more about getter function: here