this
always refers to the caller of a function. If you call a function like person.init()
then this
refers to the Person
instance. If you call a function without specifying the this
like alert()
then it will refer to the window
.
Is "this" referring to the Class class or Klass class?
Neither, exactly. In the end, it refers to the new Person
instance that you're creating.
Why is "this" being applied to "this.init"? Isn't this default behavior?
If you don't prefix with this
then it's going to assume you're talking about some other variable/function, typically a global unless you have a closure.
Are they both the same "this"?
If by both you mean Class
and klass
then no. As the first question states: this
is determined by the caller or new
.
One thing that may be confusing is the use of apply
. All that apply
does it allows you to set the caller of a function before calling it and pass any arguments as an array. The reason they do this is to allow the user to pass their own arguments. For example, say we have the following two init functions:
Person.prototype.init = function(name) {
this.name = name;
};
Person2.prototype.init = function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
};
klass
needs to have some way of passing in those arguments to the init functions. It does this using apply
. So the following are functionally equivalent:
var klass = function(a, b) {
this.init(a, b);
};
// This one can take ANY number of arguments, not just two
var klass = function() {
this.init.apply(this, arguments);
};
This works because arguments
is essentially an array of the passed arguments.