Answer the question
In order to leave comments, you need to log in
Is this OOP behavior logical in javascript and is it different from c++ and java?
https://jsfiddle.net/k3wrstLy
class A {
foo() {
this.bar()
}
bar() {
console.log('bar')
}
}
class B extends A {
bar() {
super.foo()
console.log('bar 2')
}
}
let b = new B
b.bar() // Uncaught RangeError: Maximum call stack size exceeded
super.foo()
withA.prototype.foo()
Answer the question
In order to leave comments, you need to log in
The thing is that this
in A.foo
refers not to A
, but to the instance B
. And the search for a method goes along the prototype chain, starting from the top, so it never reaches A.bar.
It is pointless to argue whether this is logical or not - it's just the way it is and you need to accept such behavior, understand it and use it.
And no, in Java and C++ the behavior is not like that. In general, in javascript, inheritance is prototypal and there are quirks with features with a call context, so the understanding of OOP familiar from other languages \u200b\u200bis not always working in it.
You say that as if there is some kind of reference OOP, stored in the Chamber of Weights and Measures in Paris. OOP is a set of principles that can be interpreted in different ways (Alan Kay, EMNIP, said: "I invented the term OOP, but I didn't mean C++"). In JS, there were no classes at all until recently, and even now it is a thin layer of syntactic powdered sugar over prototypes.
When we access a property of an object in JS, the engine first looks for that property in the object itself. If the property is not found, then we go to the object, which is written as the prototype of this object, and look in it. We repeat this step until we find a property or reach Object.
When we call a method on an object with a dot (of type b.bar()
), it is executed in the context of that object b
.super.foo()
skips the first step in finding the property, takes the method directly from the prototype's prototype, and also executes it in the b
. And in the context b
, the bar method overrides the parent method, so we get an infinite recursion, which is forcibly terminated by the engine.
What should be in Java / C ++, I will not tell you, unfortunately. Perhaps there will be the behavior you expect.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question