thomaschan wrote
Since every constructor should return 'this', does it has a default 'argument 0' which named 'this', just as the method?
Constructors do not have
this as a default argument. The object doesn't exist when the constructor is called so there in no pointer to pass yet. Argument 0 is the first real argument, like a function.
When I use the JackCompiler to output this file, it appears to be like this:
function SquareGame.new 0
push constant 0
call Memory.alloc 1
pop pointer 0
push pointer 0
return
Only the compiler knows how much memory is needed for the object's variables, so it must generate code that calls Memory.alloc() to allocate the memory block required to hold the object. In your test case, the SquareGame object had no "fields" declared, so 0 was passed to Memory.alloc().
The real SquareGame has 2 fields so the constructor will start with "push constant 2".
Effectively, the constructor is doing
this = Memory.alloc(
number of fields );
// Initialize fields ...
return this;
--Mark