0

Can I replace this by var in Javascript objects

15th Apr 2020, 1:36 PM
Youssef Ashraf
Youssef Ashraf - avatar
1 Odpowiedź
+ 1
Your question is not really clear ^^ This is this, and can't be assigned (sort of constant, but not strictly imutable as its value depends of context). You could "replace this by a variable" (since you shorten "var" and aren't talking about the keyword) in a sense. It will be local to the constructor function, and only accessible from inside, not outside... but could be used to implement kind of protected properties: function MyO() { this.val = 42; var local_val = "forty-two"; Object.defineProperty(this,"prop", { get: function() { return local_val; }, set: function(str) { if (typeof str=='string') local_val = str; else throw new Error('prop accept only string'); } var o = new MyO(); console.log(o.val); // 42 o.val = 'foo'; console.log(o.val); // foo console.log(o.local_val); // undefined console.log(local_val); // undef var error console.log(o.prop); // forty-two o.prop = 'bar'; console.log(o.prop); // bar o.prop = 42; console.log(o.prop); // custom error
16th Apr 2020, 12:40 AM
visph
visph - avatar