I have debugged the code with Firebug. Let's examine the line below from "main" function step by step : A().test1().problem();

1) A()
"The keyword "this" isn't a function(class) object. It is always the "window" object, that is extended line by line in the running time by the properties/methods of the current object (in our case: A's function object). So When we reach the end of A() (i.e. "return self"), the "this" object content is the following:

all properties/methods of the "window" object

test1() and problem() methods of A

2) A().test1()
test1() method has the line "B().test2();". So it calls as next B()

2.1) B()
When we reach the end of B() (i.e. return self), the "this" object content is the following:

all properties/methods of the "window" object

test1() method of A
[problem() method of A gets lost, because it is overwritten by the problem() of B]

test2() and problem() methods of B

2.2) B().test2()
This runs as expected and is OK. So we are finsihed with A().test1().

3) A().test1().problem();
And this calls the B's problem() method, although i want to call the A's problem() here.

So what is the proper way to save the online state of the "this" object?
(It's clear ,that "self" has no effect at all here since it is a reference (like in C) to "this" object.)

I could clone the "this"-object's state at the beginning of every constructor, i.e.:
instead of

var self = this;

how about that

var self = this.clone();

But i'm not sure if it's a good idea. Cause cloning the state of "this" for every newly created object would kill the memory in a large framework, wouldn't it?

I'm sure that i'm not the first person that confrontates with this problem. My Google searche gave me not much. So again what is the proper way to save "this"? How can i let A's problem() get called in this example instead of B's problem()?

Should i always call a function than by using the "new" keyword? Does it have any side effects ? (e.g. like creating duplicate function objects)
–
moller1111May 2 '13 at 5:03

1

@moller1111 no, if you are working with objects as you are in this case you have to use new
–
Arun P JohnyMay 2 '13 at 5:12

thank you. i will accept your answer, because you were first and you answered the additional question as i wanted. For anyone who reads this comment: Please look at the other posts for "self" tip of "Umur Kontacı" and the recommended book link of "jdigital" below.
–
moller1111May 2 '13 at 5:19

new keyword in javascript has a feature that sets this variable to the new instance. If you just use var x= A(); than this in A function would be window (ie. the global context).

For these simple settings, you do not need to use var self = this; until you need a callback, but for convenience, you can do that without any side effects. Setting a variable's value to this to make it consistent is perfectly right and is very common, the variable's name is usually that instead of self but that's just sugar.