A Strange Case of Inheritance Behavior

While working on some code for the Zuora SOAP API, I got bitten by a strange case of inheritance behavior. It seems this is related to what self is bound to during the execution of the statement. Here it is, distilled to its essentials:

class Parent def self.foo "parent foo" end def self.bar puts "parent bar" puts self.foo end end class Child < Parent def self.foo puts "child foo" end def self.bar puts "child bar" super end end puts Child.bar

Intuition will tell you that when you call Child.bar, since the method called super, you would remain in the Parent context. So when the Parent.bar method calls self.foo, you would expect it to remain in the same context.

This is not the case; it is as if the binding of self remains with the Child class. That is why, even though self.foo is called in the Parent class, Child.foo is called instead.

I asked my colleague Aaron, who was once a Python programmer, to give me equivalent Python code to run:

class Parent(object):
	def foo(self):
		print("Parent foo")
	def bar(self):
		print("Parent bar")
		return self.foo()

​class Child(Parent):
	def foo(self):
		print("Child foo")
	def bar(self):
		print("Child bar")
		return super(Child, self).bar()

c = Child()
print(c.bar())

And the output was the same:

Child bar
Parent bar
Child foo

I’m not an expert JavaScript programmer, so I’m curious how an equivalent program would behave in JavaScript.

Update:

Lee Siong Tai kindly provided me a fiddle here: http://www.es6fiddle.net/in0c3zsi/ and interestingly, it shows the same behavior.

Jimmy Ngu also has some interesting links. Go check out our discussion at https://www.facebook.com/groups/klxrb/permalink/792231597575468/

Comments

comments powered by Disqus