N
N
netW0rm2017-03-07 11:51:11
JavaScript
netW0rm, 2017-03-07 11:51:11

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

I expect that in class B's bar() method, when super.foo() is called, class A's foo() method will be called, which will call class A's bar() method , but class B 's bar() method is called and we get an error Uncaught RangeError: Maximum call stack size exceeded
Is this behavior logical from an OOP point of view, does it happen the same way in c++ and java?
UPD:
Thanks to the commentators, I figured it out.
To get it the way I want, you need to replace the call super.foo()withA.prototype.foo()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2017-03-07
@netW0rm

The thing is that thisin A.foorefers 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.

K
Konstantin Kitmanov, 2017-03-07
@k12th

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 question

Ask a Question

731 491 924 answers to any question