Skip to content

Instantly share code, notes, and snippets.

@MarwanShehata
Created March 3, 2024 11:44
Show Gist options
  • Save MarwanShehata/a4df2dfebe3aea04c43111296c890027 to your computer and use it in GitHub Desktop.
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
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