Search This Blog

2023/09/02

Javascript OOP: Adding a property to object of class which is not defined in class

Lets consider below code snippet.

"use strict"
class MyClass {
#name
constructor(name) {
this.#name = name
}

get Name(){
return this.#name
}

set Name(value){
this.#name = value
}
}

var classObject =new MyClass("sangram");
Object.seal(classObject)

classObject.Name = "desai"
classObject.name = "sachin"

console.log(classObject.Name)
console.log(classObject.name)

Output:
/home/sangram/Documents/Study/phenix/seal.js:23
classObject.name = "sachin"
^
TypeError: Cannot add property name, object is not extensible

Explanation:
Execution of this code gives us an error that Object is not extensible.
but if we remove "use strict" ,it will not give error and print undefined
for
console.log(classObject.name)

If we comment out Object.seal then sachin is printed for
console.log(classObject.name)

Object.seal will allow calling setter
classObject.Name = "desai"

No comments:

Post a Comment