3

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 3

2

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);

2

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.

1
  • I think this is very useful for my application. Thank you!
    – sjaakoil
    Commented Mar 15, 2020 at 9:37
1

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)

2
  • Thank you for your suggestion! Is there a way to access the Class through the Instance? I want to write a generic method in the parent class that can reset a property to its initial value. I don't see how I can do it through this approach. Do you have a suggestion?
    – sjaakoil
    Commented Mar 15, 2020 at 9:27
  • instance.constructor will be MyClass
    – CherryDT
    Commented Mar 15, 2020 at 10:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.