Reputation: 560
I am having this problem with subclasses overriding class property in JS. I think the behavior in OOP is what I want, but I wish to achieve the same in JS.
class Base {
constructor () {
console.log(this.a)
}
}
class Child extends Base {
a = 1
}
new Child()
// undefined, but I expect (want) 1
How do I modify my code to log 1
?
Example in Python, that works:
class Base:
def __init__(self):
print(self.a)
class Child(Base):
a = 1
Child()
# 1 -> desirable
Upvotes: 0
Views: 110
Reputation: 560
This is what I ended up doing:
class Base {
constructor () {
console.log(this.a)
}
}
class Child extends Base {
get a () { return 1 }
}
new Child()
Upvotes: 0
Reputation: 1563
undefined
output is expected behavior. You haven't defined the property a
in the base class so it is just natural that base class constructor outputs undefined
in the console.
class Base {
constructor () {
console.log('Base constructor', this.a) // outputs undefined
}
}
class Child extends Base {
a = 1
constructor () {
super();
console.log('Child constructor', this.a); // outputs 1
}
}
new Child()
UPDATE
In Python, __init__
function is not a real constructor. Constructor is __new__
.
Upvotes: 3