All Comments
TopTalkedBooks posted at August 20, 2017

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 fired

  • this.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

TopTalkedBooks posted at August 20, 2017

My first question is: what is this kind of object (not defined as a function) called?

That is knows as object literal notation.

My second question is: What is this kind of object (defined as a function) called?

That is knows as function expression.

More Readings:

If you define an object as a function, how do you define properties on the object if you don't necessarily want them to execute when it is instantiated?

You can use this keyword to add properties or use prototype property like this:

var example = function( message ) {
    alert('message');
    this.hello = function(){
        alert('hello'); 
    }
}

Or

var example = function( message ) {
    alert('message');
}

example.prototype.hello = function(){ 
   alert('hello');
}

var e = new example('hello');
e.hello();

When using this, you need to use new keyword to instantiate the object.


Interested readings on OOP:

TopTalkedBooks posted at August 20, 2017

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.

TopTalkedBooks posted at August 20, 2017

Books

Videos

On Stack Overflow

Others

Top Books
We collected top books from hacker news, stack overflow, Reddit, which are recommended by amazing people.