admin管理员组

文章数量:1324877

Is there any difference when I explicitly return from a function vs. implicitly return?

Here's the code that puzzles me ATM:

function ReturnConstructor(arg){
    // Private variable. 
    var privateVar = "can't touch this, return ctor.";

    // This is what is being exposed to the outside as the return object
    return {
        print: function() {
            console.log("ReturnConstructor: arg was: %s", arg);
        }
    };
}

function NormalConstructor(arg){
    // Private variable. 
    var privateVar = "can't touch this, normal ctor";

    // This is what is being exposed to the outside as "public"
    this.print = function() {
            console.log("NormalConstructor: arg was: %s", arg);
        };
}

var ret = new ReturnConstructor("calling return");
var nor = new NormalConstructor("calling normal");

Both objects ('ret' & 'nor') seem the same to me, and I'm wondering if it's only personal preference of whomever wrote whichever article I've read so far, or if there's any hidden traps there.

Is there any difference when I explicitly return from a function vs. implicitly return?

Here's the code that puzzles me ATM:

function ReturnConstructor(arg){
    // Private variable. 
    var privateVar = "can't touch this, return ctor.";

    // This is what is being exposed to the outside as the return object
    return {
        print: function() {
            console.log("ReturnConstructor: arg was: %s", arg);
        }
    };
}

function NormalConstructor(arg){
    // Private variable. 
    var privateVar = "can't touch this, normal ctor";

    // This is what is being exposed to the outside as "public"
    this.print = function() {
            console.log("NormalConstructor: arg was: %s", arg);
        };
}

var ret = new ReturnConstructor("calling return");
var nor = new NormalConstructor("calling normal");

Both objects ('ret' & 'nor') seem the same to me, and I'm wondering if it's only personal preference of whomever wrote whichever article I've read so far, or if there's any hidden traps there.

Share asked Jan 9, 2014 at 23:43 NoctisNoctis 11.8k3 gold badges45 silver badges84 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

When you use new, there's an implicit value. When you don't use new, there isn't.

When a function called with new returns an object, then that's the value of the new expression. When it returns something else, that return value is ignored and the object implicitly constructed is the value of the expression.

So, yes, there can be a difference.

Implicit return only happens for single statement arrow functions, except When arrow function is declared with {}, even if it’s a single statement, implicit return does not happen: link

本文标签: Any difference between explicit and implicit return in javascript functionStack Overflow