Too bad you are not using strict mode; then what you think is the
[Window]
object referenced by this would be the object
undefined
, which is much better for safe programming. Also, strict mode would not allow your
Clock = function ()
with missing
var
keyword.
So, my first advice: during development, always start all your scripts with
"use strict";
See also:
Strict mode - JavaScript | MDN[
^].
If you really want, you can switch "strict" off when your development is done.
Your other problem is the way of thinking. You say "…without using the this keyword", as if "this" was the hassle. It's not a hassle, it's a feature you really need to understand. First of all, you should understand that "this" in JavaScript is very different from "this" in OOP language; and this is so, first of all, because of the nature of functions which are first-class citizen objects. You make some simple mistake which I cannot see because you did not show some relevant part of code. If something does not work for you, instead of getting rid of it, you should try to understand it. But I can explain what can go on.
And, finally, your problem is: you are writing too much code before you sort out some fundamentals. Let me shorten it down to show what you could observe:
function f() { writeLine(this); }
var Clock = function () {
this.node = 2;
}
Clock.prototype = {
start: function ()
{
writeLine(this.node);
f();
},
};
function f() { writeLine(this); }
var cl = new Clock();
cl.start();
In this code sample,
writeLine
is my debug/playground function. If you call
start
, you will see that "this" is really reference your
Clock
object, because you reference it inside a function which is an instance member of this object. When you call
f
(or
setInterval
, "this" would be
undefined
, because these functions are as much of objects as any other objects; and these objects are not properties of another object; they are on the top level. And, in your code shown, there are no such "this" cases; you have only
this.tick
and
this.interval
. First will work as the clock object property, and, unfortunately, you did not show where you define
interval
. If it is not defined, as shown in your code fragment, this is the real problem, and "this" is not guilty. :-)
—SA