October 1, 2013
Creating an Instance
new keyword exists and it does exactly what you would expect.
Creation looks wrong ?
What looks a little weird is the missing
Fruit. This is a bit unnatural to me. To get the parenthesis I was looking for I had to use a
function() to wrap up my current functionality. When doing this, the function has a little bit of a different syntax, but for the most part things are the same. The new definition introduces the
this keyword, which is used to reference the current object. Same as in many other languages.
This gives me the initialisation I are looking for. Also, I can conveniently pass in variables to the constructor, so with mild modification I can pass in price and name instead of using three lines to create the desired object.
More familiar Instantiation
Now I can easily create an object and it will look almost exactly like it would in another language like Java.
var inside the function will actually be attached to the global namespace. My
Fruit example does not do this, but often times other objects will. To avoid this, you use a self executing function object.
Make it inheritable
Everyone is well aware that there is more than one type of fruit ( or maybe I just spilled the beans ). To incorporate this into my example, I want to keep the functionality that i have for
Apple has a fixed name and price. Below is a fairly easy example of inheriting an Object’s prototype.
The code is pretty straight forward. 2 things to note.
1. The constructor of Apple takes no arguments. To call the constructor of the base object you use the
call method to execute a function with a specified
this variable. Also, allows for passing in other variables as you can see above. The constructor for
Apple should simply be
2. To take advantage of the functions defined in the
Fruit prototype I simply set our new object’s prototype equal to the base prototype. All the methods in
Fruit are now available in our new object.