-4

What is the purpose of constructor and new operator in javascript and why it is used on functions as we already have function calls in which returned value is reliable. what is the purpose of this constructor as it gives the value same as the function call?

  • 2
    Do you need an explanation of what OOP is and why it's useful? 'Cause that's way too broad to answer here… – deceze Mar 14 '18 at 10:17

1 Answers1

0

If you wish to emulate a class functionality in your application you can use functions as impromptu classes to store and handle objects.

You can also scope these classes to your local function

function Foo() {
   this.bar = new Date();
}
Foo.prototype.getDate = function() {
   return this.bar;
}

var foo = new Foo();
console.log(foo.getDate());

+function() {
  var Foo = function() {
     this.bar = new Date();
  }
  Foo.prototype.getDate = function() {
     return this.bar;
  }
  /**
   * scoped Foo works
   */
  var foo = new Foo();
  console.log(foo.getDate());
}();
/**
 * Outside of function scope, Foo is unkown
 */
var foo = new Foo();
console.log(foo.getDate());
Tschallacka
  • 24,188
  • 10
  • 79
  • 121