0

This is going to be a tricky question. Having a constructor:

var Constructor = new function(){
this.a = 'a';
this.b = 'b';
}

we can create an object:

var obj = new Constructor();

this in Constructor refers to window but when calling new Constructor() some magic is being done: now this is finding out the scope of a function it is in (how exactly is it working?) and assigning only that scope to obj returns it. So basically it is doing something like:

var Constructor = new function(){
var this = {some object having variables needed for every object (like __proto__)}    
this.a = 'a';
this.b = 'b';
return this;
}

Can anyone tell me how it is this mechanism of creation of new object in JS is working in low level? What exactly is being done underneath when calling new?

  • and what's the point of `new function()`? – Matías Fidemraizer Sep 17 '14 at 15:08
  • @MatíasFidemraizer: [It's a mistake](https://stackoverflow.com/questions/10406552/is-it-right-to-think-of-a-javascript-function-expression-that-uses-the-new-key) – Bergi Sep 17 '14 at 15:09
  • *"now `this` is finding out the scope of a function it is in"* You seem to be confusing scope and `this`. They actually don't have anything to do with each other (other than that in each environment (scope), there is a binding `this`). – Felix Kling Sep 17 '14 at 15:11
  • Also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – Felix Kling Sep 17 '14 at 15:15

1 Answers1

1

"new SomeFunction()" is creating a new object, and calling SomeFunction with that object as "this".

Consider this:

function SomeFunction() {
    this.hello = "Hello, world";
}
var myObj = new SomeFunction();
myObj.hello; // "Hello, world"

var myObj2 = {};
SomeFunction.call(myObj2);
myObj2.hello; // "Hello, world"
folkol
  • 4,752
  • 22
  • 25