How to access a default class property from an object?

Viewed 63

I have the following challenge, that I did not succeed. And I could not find an example of someone who bumped on the same problem.

class MyClass {
    name = 'default name'
}

let instance = new MyClass();
instance.name = 'new name';

# At this point I want to be able to access the default 'name' of my class (value: 'default name')

I am curious about how to approach this the best.

3 Answers

Given the code in the question exactly, it's not possible unless you create a new instance. With

name = 'default name'

you assign to the name property of the instance object. Then with

instance.name = 'new name';

you overwrite the name property of the instance object. The 'default name' no longer exists anywhere in the prototype chain.

So, create a new instance to run the class field again:

class MyClass {
    name = 'default name'
}

let instance = new MyClass();
instance.name = 'new name';

const newInstance = new MyClass();
console.log(newInstance.name);

A better pattern would be to put the default value on the prototype. That way, you can examine the property on the prototype or the property on the instance:

class MyClass {
    
}
MyClass.prototype.name = 'default name';

let instance = new MyClass();
instance.name = 'new name';

console.log(instance.name);
console.log(MyClass.prototype.name);

As mentioned by the other answers, there is no straight-forward way, you have to create a new instance.

However, if you need this more often, you could create the instance once and reuse it:

class MyClass {
  name = 'default name'
}

MyClass.prototype.defaults = Object.freeze(new MyClass())

// ------------

let instance = new MyClass()
instance.name = 'new name'
console.log(instance.name) // new name
console.log(instance.defaults.name) // default name

I'm additionally using Object.freeze to prevent accidental modifications to the default instance.

You could also assign to MyClass.defaults, but then you'd have to use instance.constructor.defaults.name or MyClass.defaults.name.

You can create a new temporary instance and get the name

class MyClass {
    name = 'default name'
}

let instance = new MyClass();
instance.name = 'new name';

console.log((new MyClass()).name)

Related