Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications and libraries
All
Stack Overflow 17
This Year
Stack Overflow 2
This Month
Stack Overflow 3
As Pointy has pointed out, in his answer
The usual way to deal with this is to augment the object's prototype
constructor
property after assigning to theprototype
I can't recommend Stoyan Stefanov's Object Oriented JavaScript enough which covers Prototype and Inheritance in some detail (get the second edition if you can as it addresses some critiques of the first edition).
I saw this pattern in a book called Object-Oriented Javascript by Stoyan Stefanov.
http://www.amazon.co.uk/Object-Oriented-Javascript-Stoyan-Stefanov/dp/1847194141
Like @Chales Tuang mentioned, I got the expected output on
jsfiddle
The only explanation I could possibly think of for the case where you get same output in each call to console.log, is that the browser is applying the principle that objects are live in Javascript, as shown by Stoyan Stefanov in his book Object Oriented Javascript
As a result, the when you call console.log, it sees the latest, up-to-date property(ies) of the object, even though the object was augmented after the call, in as much as the update is within the scope of the call, it just grabs the current updated state of the object.
That's my thought on this, anyway.
Books
Videos
On Stack Overflow
Others
Some good sources for Object-Oriented JavaScript and JavaScript in general...
Online Articles
Books
I hope this helps.
Hristo
That is a self executing anonymous function. The () at the end is actually calling the function.
A good book (I have read) that explains some usages of these types of syntax in Javascript is Object Oriented Javascript.
That is knows as object literal notation.
That is knows as function expression.
More Readings:
You can use
this
keyword to add properties or useprototype
property like this:Or
When using
this
, you need to usenew
keyword to instantiate the object.Interested readings on OOP:
this is very good question)
in JS functions are objects, so by calling
ninja.changeName("Bob")
you go straight to ninja's method.changeName()
if
ninja.changeName
was called no actions outside this method will be firedthis.changeName ( name);
- is constructor actions, they are applied to ninja object on creation only (to extend the newly created object with property name)take a look at this great book on OOP in JS