Can you please tell me how to block a variable change in JS? can somehow undo its change.

Ajax('POST', '/Controller/path', {}, function (result) { window.test = result.test; //ΠΊΠ°ΠΊ Π·Π°Π±Π»ΠΎΠΊΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒ ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΠ΅ этой ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½ΠΎΠΉ. Π’Π΅Π΄ΡŒ Π΅Ρ‘ ΠΌΠΎΠΆΠ½ΠΎ ΠΈΠ·ΠΌΠ΅Π½ΠΈΡ‚ΡŒ Ρ‡Π΅Ρ€Π΅Π· консоль. }); 
  • Where is she? global? in function? in the method? in the module? in the component? - Alexey Shimansky
  • more importantly what kind of variable it is - Grundy
  • Please specify the question. Do you want to block the value of a variable in javascript or do you want to block the value of one or another html attribute? - Elvin No Matter
  • @ Alexey Shimansky in a global facility. - Tsyklop
  • @ElvinNoMatter variable js - Tsyklop

3 answers 3

This can be done by declaring a variable using Object.defineProperty.

Example:

 Object.defineProperty(window, "test", { value: "НСизмСняСмоС", writable: false, // Π·Π°ΠΏΡ€Π΅Ρ‚ΠΈΡ‚ΡŒ присвоСниС "test=" configurable: false // Π·Π°ΠΏΡ€Π΅Ρ‚ΠΈΡ‚ΡŒ ΡƒΠ΄Π°Π»Π΅Π½ΠΈΠ΅ "delete test" }); 

Important! Without use strict write operation "silently" will not work. If use strict mode is set, then an error is additionally generated.

  • that's just it will not help if the debugger to save the value that is assigned to this property. It can still be changed as you please - Grundy

Well, there is no such possibility in the current standard. There are some agreements, for example, if a variable name begins with _ then its value should not be changed directly.

 _superConst = "super"; //ΠΌΠ΅Π½ΡΡ‚ΡŒ ΠΌΠΎΠΆΠ½ΠΎ, Π½ΠΎ дСлая это Π²Π°ΠΌ Π±ΡƒΠ΄Π΅Ρ‚ стыдно 

But, I hope, in the near future, in the new js standard, the variable declaration as const will be available. The value of a variable declared as const physically forbidden to change.

 const _superConst = "super"; //ΠΌΠ΅Π½ΡΡ‚ΡŒ Π½Π΅ получится 

You can use this feature now if you connect babel or any other js code translator that can turn es6 into es5 javaScript.

    let's say you have an object named Person and you want to create a static value for it.

     function Person(){ this.name = "Peter"; } 

    then create a variable and equate the instance of this object

     var p1 = new Person(); 

    source code

    • This is the answer to the wrong question. - Igor