Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of keyword "new" in javascript

I've read the topic about "new" keyword in javascript (What is the 'new' keyword in JavaScript?). But, i'm still in the fog; let's talk about this example :

var foo = function() {
    return {
        setA: function(a) {
            this.a = a;
        },
        readA: function() {
            console.log(this.a);
        }
    };
};

And now what's about these two pieces of code :

One:

var bob1 = foo();
bob1.setA(10);
bob1.readA();

Two:

var bob2 = new foo();
bob2.setA(10);
bob2.readA();

I cannot see any differences at my level. So what is the gain to use the keyword "new" ?

like image 717
user1983120 Avatar asked Apr 08 '14 09:04

user1983120


1 Answers

If your function returns object directly, then you do not need an new operator. The new keys does more than that.

Lets say

function Animal(kind, name) {
   this.kind = kind;
   this.name = name;
}

Animal.prototype.walk = function() {
    console.log('Walking');
}

Then you are doing

 var animal = new Animal();

Javascript engine will do following things

  var o = Object.create(Animal.prototype)
  Animal.apply(o, arguments);
  return o;

Object.create will do the prototype inheritance of the prototype object of Animal function. So animal object will have its own properties and its inherited property.

like image 131
Fizer Khan Avatar answered Nov 07 '22 22:11

Fizer Khan