Reputation: 94
A terrible title I know, but it's a problem that's easier to define with an example.
I have a code structure which involves multiple levels of inheritance, my example displays only two as this is sufficient to demonstrate the behaviour.
var parent = function() {
var self = this;
self.parent = function() {
self.test();
}
self.test = function() {
alert('parent');
}
};
var child = function() {
var self = this;
self.child = function() {
self.test();
self.parent();
}
self.test = function() {
alert('child')
}
};
child.prototype = new parent();
var o = new child();
o.child();
I would expect calling the child method would display two alerts, both displaying the text 'child', however this is only true for the first alert, the second displays 'parent'
See the fiddle here: http://jsfiddle.net/vc8t7fbq/1/
Can anyone explain why this is happening?
Upvotes: 1
Views: 52
Reputation: 17064
o.child();
calls for child()
method on o
, which is:
self.child = function() {
self.test();
self.parent();
}
self.test()
runs and calls the method declared right underneath it, inside child
as well:
self.test = function() {
alert('child')
}
So this is the first alert you see.
The second, is when self.parent()
runs. Since the prototype of child
is parent
, invoking self.parent()
calls to:
self.parent = function() {
self.test();
}
I assume your confusion is here - why self.test()
calls to the parent instead of the child?
The reason is that you have this line: var self = this
. This means that the this
was already put inside self
, and it is not reevaluated. Meaning, self
is the parent.
For evidence, if you switch the method's body to:
self.parent = function() {
this.test(); //will alert "child"
}
You would see 2 "child" alerts, since this
evaluates to the child.
Upvotes: 3