After Update and show在控制台cartypeSafari但是inside car objectFiat期望的inside car objectSafari
我不想使用car。type = Safari在更新函数中,因为我在多个对象中使用了//cartype。
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>
看来你唯一的希望是将car.type
设置为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>
您可以使用getter函数从car.type
获取全局cartype
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>
了解getter函数的更多信息:这里