Created
March 3, 2024 11:44
-
-
Save MarwanShehata/a4df2dfebe3aea04c43111296c890027 to your computer and use it in GitHub Desktop.
Metaprogramming (Advanced):
Symbols can be used for advanced metaprogramming techniques like property name creation and dynamic property access. However, these use cases are less common and typically require a deep understanding of JavaScript intern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const serializableSymbol = Symbol.for("serializable"); | |
class User { | |
constructor(name) { | |
this.name = name; | |
this[serializableSymbol] = ["name", "age"]; // Mark 'name' and 'age' for serialization | |
} | |
getSerializableProperties() { | |
const properties = []; | |
for (const key in this) { | |
if ( | |
this.hasOwnProperty(key) && | |
key !== serializableSymbol && | |
this[key][serializableSymbol] | |
) { | |
properties.push(key); | |
} | |
} | |
return properties; | |
} | |
} | |
const user = new User("Alice", 30); | |
const serializableProps = user.getSerializableProperties(); | |
console.log(serializableProps); // ['name'] (only 'name' is marked as serializable) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment