Is calling a function that returns a function with new different than just invoking it normally?

前端 未结 3 1759
南旧
南旧 2021-01-21 21:51

So let\'s say I have a javascript function

function A(){
    return function(){
        console.log(\'something\');
        return new B();
    }
}
相关标签:
3条回答
  • 2021-01-21 22:01

    When you call the function without "new", what is it that you suspect "this" is pointing to? It'll be "window." Updating that is slower than updating the freshly-built new object you'll be using when you invoke it with "new".

    0 讨论(0)
  • 2021-01-21 22:22

    Since that function has an explicit return and makes no use of this, there is no difference in the result of running it with or without new.

    0 讨论(0)
  • 2021-01-21 22:22

    Others have given answers about the result (is the use of new equivalent to not using it or not?), but let me explain why following two results are equivalent:

    var no_new = A();
    var with_new = new A();
    

    The relevant part of the ECMAScript is section 13.2.2 (I will omit and simplify some information and adapt the contents of that section to suit this answer). This is what happens when new A() is executed:

    1. A new object is created.
    2. The prototype of function A is examined:
      1. If the prototype of A is an object, newly created object's prototype is set to A's prototype.
      2. If not, newly created object's prototype is set to the default prototype of Object.
    3. Function A() is called, and the result is examined.
      1. If the result is an object, the result will be the return value of new.
      2. Else the newly created object will be the return value of new.

    In your case, the execution will take the path 3.1, aka new operator will return a reference to the inner anonymous function, same as the function call without new.

    So, both variables no_new and with_new will have a reference to a function in the following form:

    function () {
        console.log('something');
        return new B();
    }
    

    (Note that no_new and with_new are equivalent but not identical. They do not refer to the same object: JSFiddle)

    function A() {
        return function(){
            console.log('something');
            return new B();
        }
    }
    
    function B() {
    }
    
    var no_new = A();
    var with_new = new A();
    
    alert(no_new);
    alert(with_new);
    
    var are_they_same = (no_new === with_new);
    alert(are_they_same);

    0 讨论(0)
提交回复
热议问题