Why is SuperClass:initialize() different from SuperClass.initialize(self) in lua?

Viewed 29

When using middleclass I encountered a strange problem:

ParentClass = class('ParentClass') 

function ParentClass:initialize(param)
   self.param = param
end

Now this will work:

Child1 = class('Child1', ParentClass)

function Child1:initialize(param)
  ParentClass.initialize(self, param)
end

But this wont:

Child2 = class('Child2', ParentClass)

function Child2:initialize(param)
  ParentClass:initialize(param)
end  

Creating Children like Child2 will result in a modification of param not for the single instance but for all children that inherit from ParentClass.

It took me quite a long time to identify this problem as I was sure that Object:function() is just syntactical sugar for Object.function(Object) and thus should be the same. This seems somehow not to be a problem of middleclass because a different OO library I used before showed similar problems...

What am I missing here?

1 Answers
function Child1:initialize(param)
  ParentClass.initialize(self, param)
end

is equivalent to

function Child1:initialize(param)
  ParentClass.initialize(Child1, param)
end

So self in

function ParentClass:initialize(param)
   self.param = param
end

will refer to Child1

While

function Child2:initialize(param)
  ParentClass:initialize(param)
end  

is equivalent to

function Child2:initialize(param)
  ParentClass.initialize(ParentClass, param)
end

so self in

function ParentClass:initialize(param)
   self.param = param
end

will refer to ParentClass

So snippet 1 will initialize Child1 while snippet 2 will initialize the base class.

Related