What is the difference between calling function () and calling new function ()?

0

I have this code

function DoPlayer() {

  this.name = name;
  this.number = function() {
    prompt('Ingresa un numero', "");
  };

}

I would like to understand the difference between calling the function DoPlayer() and doing new DoPlayer() .

    
asked by Eduardo Sebastian 24.05.2017 в 04:33
source

1 answer

3

new funcion() creates a new object and calls funcion setting that new object is the value of this for the function. (so funcion makes the role of constructor / allows you to manipulate this ). Also, new funcion() returns that object so that you can use it later, which fulfills the role of instance of the object.

When you invoke funcion() directly, the value of this depends on the context. If the function is invoked from the global scope (eg direct from a tag <script> ), then this carries the value of window . It does not use the this of the current context.

Example:

function funcion() {
  
  console.log(this === window);
  
  this.otraFuncion = function() {
    console.log(this === window);
  }
  
}

// invocas a funcion, this es window.
funcion(); // true

// this es un nuevo objeto creado para tal fin.
var instancia = new funcion(); // false

// this es window
window.otraFuncion(); // true

// this es la instancia
instancia.otraFuncion(); // false

Another thing to keep in mind is that the value of this depends on who invokes the function and not where it is declared .

This is a concrete example: the setTimeout function invokes the callback from the context of window . Therefore the value of this within the callback is window .

Example:

function funcion() {
  console.log( this === window );
  
  setTimeout(function() {
    // Aqui se aprecia que this depende de quien invoca y no del lugar donde una funcion esta declarada.
    console.log( this === window );
  }, 0);

}

funcion(); // true true
new funcion(); // false true

Salu2.

    
answered by 24.05.2017 / 04:52
source