-2

I'm learning JavaScript and I just came up with this thought

Why do I need 'new' to create an object?

function a(){};
var b = new a();
var c = {};
c.__proto__ = a.prototype;

If I create an object and point it's __proto__ to the constructor's prototype. Is it the same way to create an object using new?

franose
  • 35
  • 5

3 Answers3

0

In your scenario, they would be equivalent (although __proto__ has been historically discouraged because it wasn't properly standardized), but only because the definition of a is empty.

If a would perform some initialization, it would not be done for c.

As for why new is necessary, the difference between calling a() and new a() would be the context object (this would be the global object or the newly created object).

fortran
  • 74,053
  • 25
  • 135
  • 175
0

In principle, you do not need anything. Javascript just has slightly different ways of creating objects which (of course) work slightly different. In your examples:

function a() = {}; // syntax error, correct syntax is function a() {}
var b = new a(); // creates a new instance of a - assuming a is a constructor function
var c = {}; // creates a new object literal
c.__proto__ = a.prototype // assings the prototype of function a to __proto__ of c

As a basic rule of thumb, if you simply want to create an object use the object literal way. If you want to use the constructor pattern you wanna use the new keyword to create instances using the constructor - you can also create instances manually but new is syntactic sugar. I would try to avoid directly assigning objects to the __proto__ since that is usually done internally. Another way to create objects based on other objects is using Object.create({}).

The latest ES syntax introduces the class keyword to abstract out the constructor pattern. This is a polarizing feature of the language. Read more here.

Hope it helps, happy learning!

Fredi
  • 1
  • 4
0

firstly,the __proto__ only support on safari,chrome,firefox,not supported by IE,and which has not yet become a standard.

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

Animal.prototype.run = function() {
    console.log(this.name + 'can run...');
}

var cat = new Animal('cat');

to simulation the new process as below:

//Simulation process
new Animal('cat')=function(){
    let obj={};  //create an empty object
    obj.__proto__=Animal.prototype; 
    //obj->Animal.prototype->Object.prototype->null
    return Animal.call(obj,'cat');// bind this to the instantiated object
}
Alvin
  • 298
  • 2
  • 14
  • Thanks! So the real simulation for `new` is much more complicate because the real constructor is not empty. The keyword `new` helps to simplify the process? – franose Sep 13 '17 at 07:24