The code snippet below is from ‘Javascript Web Applications’ by O’Reilly. In it, the author explains that using the new keyword ordinarily returns a this context, unless you specifically return something else– below, he’s returning ‘ a function that would set up a new class’, in his words (pg 7):
var Class = function(){
var klass = function(){
this.init.apply(this, arguments);
};
klass.prototype.init = function(){};
return klass;
};
var Person = new Class;
Person.prototype.init = function(){
// Called on Person instantiation
};
// Usage:
var person = new Person;
I’m not following this. What does returning klass do here? in the case of var Person = new Class, am I not getting a new Class object, but rather, some function that can create a Class? That’s what I’m reading from the text but it’s confusing to me.
Before getting where he’s going, the first step is getting
this.There are three things
thiscan typically point to.If you have a function which is a property of an object:
In this case,
thispoints to whatever object owns the property (whatever is one-dot ahead, at the exact moment the function is called)So
thisis decided at the last possible second.Functions also have properties of their own, like objects.
Two of these are functions called
.calland.applyand they allow you to run the function, but tell the function exactly whatthisis.Remember how
say();didn’t work on its own?The next part of
thisis the one we’re most used to in object-oriented languages; usingthisalong withnewto make a new instance of a class:Basically, inside of this constructor function (or any function, as constructors aren’t special in JS), the function starts by checking if
newwas called.If it was, set
thisto a brand new object, regardless of whether it’s part of an object:So it’s like the function is saying
if (new) { this = {}; }at the top of the function.I said there were three possibilities.
The third is that
this === windowIf you use a function where
thisisn’t an object (either through call/apply, or as a property of an object) andnewwas not used to make a new object, thenthispoints atwindow.That is why
say();did not work on its own, before;window.say();is the equivalent.Back to
newfor a second —newdoes a couple of other things.Namely, it sets the value of the object’s constructor:
It also gives objects made from that constructor access to the
prototypeobject, which all instances share.So now, look at what’s going on inside of Class/Klass:
We’re creating a
new Class();object.Inside of the
Classfunction,this = {};(because ofnew).Then, we’re making a new “constructor” function,
klass.Then, we’re setting the prototyped
initfunction, which we.applyto any newthis(in theklass, at the time a new instance is called).Then we’re returning the klass.
klass is actually what you’re calling when you make a new Class
And when you call for a new object of a class, klass is being run.
Hope that helps with
newandthisand.callandClass/klass.