Is using new in Javascript the same as not using it?

Consider this code:

function klass( z ) { this.a = z; return this; } var b = klass( 5 ); var c = new klass( 9 ); 

When I run it in Chrome and check the console, b turns out to be of type DOMWindow , and c is of type klass .

Although both have property a, in fact both are instances of the class.

  • Is it using or not using new ones, the same thing?
  • Same in this example, but different in other situations?
  • Are there differences in performance or behavior?
+6
source share
3 answers

When a function like this is called

 klass(6); //called function invocation 

this will set the global object or, if you are in strict mode, undefined

As a result, the first example (without new ) will return a global object with a new property a attached. In strict mode, it throws an error, since this will be set to undefined , and you cannot add the a property to undefined .

When calling a function with new

 new klass( 9 ); //called constructor invocation 

this value is set to a new object and implicitly returned from the function - no need to say return this

For completeness, when you call a function as a method for an object:

 foo.method(); //called method invocation 

this will be set in the foo object in this case.

And when you call the function using (or calling)

 method.apply(foo) //called apply invocation 

this set to whatever you specify - foo again

EDIT

I mentioned strict mode in my answer. A page uses strict mode if it has

 "use strict" 

at the very top.

+6
source

Without new your function will only work on what this attached to, in your case, DOMWindow. A new instance is not created, property a set to the window object. A method call captures the previous result twice.

Try the following:

 var b = klass(5) log.info(ba) log.info(b == window) // b is actually the window object log.info(window.a) // also 5 var c = klass(6) log.info(ba) // now set to 6 log.info(c == b) // c and b are the same 
+6
source

This is absolutely not the same:

 var a = klass(42); console.log(aa); // 42 var b = klass(69); console.log(ba); // 69 console.log(aa); // 69 

If you do not call new , you do not get anything new.

+3
source

Source: https://habr.com/ru/post/904366/


All Articles