在ES5中渣刷,一般利用window對(duì)象來(lái)定義常量苗桂,思路是將變量綁在window上,并設(shè)為只讀狀態(tài)趴泌。
代碼:
Object.defineProperty(window,"PI",{
value:3.14,
writeable:false,//只讀
});
console.log(window.PI);
ES6中舟舒,則可以直接通過(guò)const來(lái)聲明常量。
const PI = 3.14;
console.log(PI);