Javascript: Function, Object, new …a little bit of confusion












0















in web I read:




"Well, Javascript, or better ECMAScript, is an Object Based Language so..
Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript where an Object is a "bag" of properties and methods..."




and:




When a function is invoked with “new” keyword then the function is known as constructor function and returns a new instance. In such cases, the value of “this” refers to newly created instance.




Now, my code:



function fe(){
var i;
var j = 0;
return j;
};
process.stdout.write("fe --> "); console.log(fe); // [Function: fe]
process.stdout.write("fe() --> "); console.log(fe()); // 0

var vfe = new fe();
process.stdout.write("vfe --> " + vfe + " - "); console.log(vfe); [object Object] - fd {}




var fd = function(){
var i;
var j = 0;
};
process.stdout.write("fd --> "); console.log(fd); // [Function: fd]
process.stdout.write("fd() --> "); console.log(fd()); // undefined

var vfd = new fd();
process.stdout.write("vfd --> " + vfd + " - "); console.log(vfd); [object Object] - fd {}


In the first I have value returned and new return an object as the last case: I have an object {} and so I could append properties and methods



in an another case:



function fe(){
var i;
var j = 0;
return fe;
};
process.stdout.write("fe --> "); console.log(fe); // [Function: fe]
process.stdout.write("fe() --> "); console.log(fe()); // [Function: fe]

var vfe = new fe();
process.stdout.write("vfe --> "); console.log(vfe); // [Function: fe]


var fd = function(){
var i;
var j = 0;
return fd;
};
process.stdout.write("fd --> "); console.log(fd); // [Function: fd]
process.stdout.write("fd() --> "); console.log(fd()); // [Function: fd]

var vfd = new fd();
process.stdout.write("vfd --> "); console.log(vfd); // [Function: fd]


In this case I have a value or a Function returned that is all but an object....
Now:
id the "Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript where an Object is a "bag" of properties and methods..." not so true in all situation?



Another situation is the following:



function fe () {
var pri_var1;
// private, not accessible from extern
function pri_fun1(){ return "pri_fun1"; }
// private, not accessible from extern
function pri_fun2(){ return "pri_fun2"; }
//static property
fe.sta_var1 = 0; //static property ....is never a good idea but...for folks!!!
//static method
fe.sta_fun1 = function(){return pri_fun2();}
//public not heritable
this.pub_fun1 = function(){return "pub_fun1";}
//public heritable
fe.prototype.pub_her_fun1 = function() { return "pub_her_fun1";}
//return fe;
}

var obj2 = new fe();
console.log("obj2 --> ",obj2);
console.log(obj2.pub_fun1());
console.log(fe.sta_fun1());


If I uncomment //return fe; the "node" say:
console.log(obj2.pub_fun1());
^



TypeError: obj2.pub_fun1 is not a function...
If I leave the comment all works as well....



A little bit of confusion about Function and Object in (again):




"Well, Javascript, or better ECMAScript, is an Object Based Language so.. Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript where an Object is a "bag" of properties and methods..."




thanks in advance



Ok...I'll try to be more precise.
I read "Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript where an Object is a "bag" of properties and methods..."
Hence a function is an object? Every function?
Take the function:



function fe(){
return 1;
};


and the following instructions:



console.log(fe);    // [Function: fe]
console.log(fe()); // 1
var vfe = new fe();
console.log(vfe); // fe {}


if I read well:
fe is a function that, being non primitive, is an "object" (what kind of object? Maybe somewhat complex type representation [Function: fe] called improperly object in a not OO way?)... but it becomes object in OO way of "bag" {} only after a new (vfe)...., but it can be also be invoked (fe()) and produce a value (1)...or can return itself or by default undefined...
Some functions could not be executed but only "instantiated"? and other function can contains functions which are classical function to execute to get a normal value but not to be instantiated???
Very, very strange behaviour...
Can I have an help in terms of naming, design and boundaries about this mess?
thanks again...










share|improve this question




















  • 1





    I don't understand. Could you please describe exactly what your question is?

    – zero298
    Nov 26 '18 at 16:23











  • return fe; overwrites the constructor function / instance behavior and instead assigns the function itself to obj2, regardless of the new. Don't return anything and you get an instance that behaves as expected. Even better: learn the new class stuff that was added to JavaScript.

    – Chris G
    Nov 26 '18 at 16:25













  • I've voting to close this as off-topic because it is too broad. You seem to have four separate questions here, none of them expressed very clearly.

    – Quentin
    Nov 26 '18 at 16:27











  • "what about functions" - they're objects as well (regardless of their kind).

    – Bergi
    Dec 15 '18 at 12:45
















0















in web I read:




"Well, Javascript, or better ECMAScript, is an Object Based Language so..
Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript where an Object is a "bag" of properties and methods..."




and:




When a function is invoked with “new” keyword then the function is known as constructor function and returns a new instance. In such cases, the value of “this” refers to newly created instance.




Now, my code:



function fe(){
var i;
var j = 0;
return j;
};
process.stdout.write("fe --> "); console.log(fe); // [Function: fe]
process.stdout.write("fe() --> "); console.log(fe()); // 0

var vfe = new fe();
process.stdout.write("vfe --> " + vfe + " - "); console.log(vfe); [object Object] - fd {}




var fd = function(){
var i;
var j = 0;
};
process.stdout.write("fd --> "); console.log(fd); // [Function: fd]
process.stdout.write("fd() --> "); console.log(fd()); // undefined

var vfd = new fd();
process.stdout.write("vfd --> " + vfd + " - "); console.log(vfd); [object Object] - fd {}


In the first I have value returned and new return an object as the last case: I have an object {} and so I could append properties and methods



in an another case:



function fe(){
var i;
var j = 0;
return fe;
};
process.stdout.write("fe --> "); console.log(fe); // [Function: fe]
process.stdout.write("fe() --> "); console.log(fe()); // [Function: fe]

var vfe = new fe();
process.stdout.write("vfe --> "); console.log(vfe); // [Function: fe]


var fd = function(){
var i;
var j = 0;
return fd;
};
process.stdout.write("fd --> "); console.log(fd); // [Function: fd]
process.stdout.write("fd() --> "); console.log(fd()); // [Function: fd]

var vfd = new fd();
process.stdout.write("vfd --> "); console.log(vfd); // [Function: fd]


In this case I have a value or a Function returned that is all but an object....
Now:
id the "Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript where an Object is a "bag" of properties and methods..." not so true in all situation?



Another situation is the following:



function fe () {
var pri_var1;
// private, not accessible from extern
function pri_fun1(){ return "pri_fun1"; }
// private, not accessible from extern
function pri_fun2(){ return "pri_fun2"; }
//static property
fe.sta_var1 = 0; //static property ....is never a good idea but...for folks!!!
//static method
fe.sta_fun1 = function(){return pri_fun2();}
//public not heritable
this.pub_fun1 = function(){return "pub_fun1";}
//public heritable
fe.prototype.pub_her_fun1 = function() { return "pub_her_fun1";}
//return fe;
}

var obj2 = new fe();
console.log("obj2 --> ",obj2);
console.log(obj2.pub_fun1());
console.log(fe.sta_fun1());


If I uncomment //return fe; the "node" say:
console.log(obj2.pub_fun1());
^



TypeError: obj2.pub_fun1 is not a function...
If I leave the comment all works as well....



A little bit of confusion about Function and Object in (again):




"Well, Javascript, or better ECMAScript, is an Object Based Language so.. Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript where an Object is a "bag" of properties and methods..."




thanks in advance



Ok...I'll try to be more precise.
I read "Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript where an Object is a "bag" of properties and methods..."
Hence a function is an object? Every function?
Take the function:



function fe(){
return 1;
};


and the following instructions:



console.log(fe);    // [Function: fe]
console.log(fe()); // 1
var vfe = new fe();
console.log(vfe); // fe {}


if I read well:
fe is a function that, being non primitive, is an "object" (what kind of object? Maybe somewhat complex type representation [Function: fe] called improperly object in a not OO way?)... but it becomes object in OO way of "bag" {} only after a new (vfe)...., but it can be also be invoked (fe()) and produce a value (1)...or can return itself or by default undefined...
Some functions could not be executed but only "instantiated"? and other function can contains functions which are classical function to execute to get a normal value but not to be instantiated???
Very, very strange behaviour...
Can I have an help in terms of naming, design and boundaries about this mess?
thanks again...










share|improve this question




















  • 1





    I don't understand. Could you please describe exactly what your question is?

    – zero298
    Nov 26 '18 at 16:23











  • return fe; overwrites the constructor function / instance behavior and instead assigns the function itself to obj2, regardless of the new. Don't return anything and you get an instance that behaves as expected. Even better: learn the new class stuff that was added to JavaScript.

    – Chris G
    Nov 26 '18 at 16:25













  • I've voting to close this as off-topic because it is too broad. You seem to have four separate questions here, none of them expressed very clearly.

    – Quentin
    Nov 26 '18 at 16:27











  • "what about functions" - they're objects as well (regardless of their kind).

    – Bergi
    Dec 15 '18 at 12:45














0












0








0








in web I read:




"Well, Javascript, or better ECMAScript, is an Object Based Language so..
Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript where an Object is a "bag" of properties and methods..."




and:




When a function is invoked with “new” keyword then the function is known as constructor function and returns a new instance. In such cases, the value of “this” refers to newly created instance.




Now, my code:



function fe(){
var i;
var j = 0;
return j;
};
process.stdout.write("fe --> "); console.log(fe); // [Function: fe]
process.stdout.write("fe() --> "); console.log(fe()); // 0

var vfe = new fe();
process.stdout.write("vfe --> " + vfe + " - "); console.log(vfe); [object Object] - fd {}




var fd = function(){
var i;
var j = 0;
};
process.stdout.write("fd --> "); console.log(fd); // [Function: fd]
process.stdout.write("fd() --> "); console.log(fd()); // undefined

var vfd = new fd();
process.stdout.write("vfd --> " + vfd + " - "); console.log(vfd); [object Object] - fd {}


In the first I have value returned and new return an object as the last case: I have an object {} and so I could append properties and methods



in an another case:



function fe(){
var i;
var j = 0;
return fe;
};
process.stdout.write("fe --> "); console.log(fe); // [Function: fe]
process.stdout.write("fe() --> "); console.log(fe()); // [Function: fe]

var vfe = new fe();
process.stdout.write("vfe --> "); console.log(vfe); // [Function: fe]


var fd = function(){
var i;
var j = 0;
return fd;
};
process.stdout.write("fd --> "); console.log(fd); // [Function: fd]
process.stdout.write("fd() --> "); console.log(fd()); // [Function: fd]

var vfd = new fd();
process.stdout.write("vfd --> "); console.log(vfd); // [Function: fd]


In this case I have a value or a Function returned that is all but an object....
Now:
id the "Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript where an Object is a "bag" of properties and methods..." not so true in all situation?



Another situation is the following:



function fe () {
var pri_var1;
// private, not accessible from extern
function pri_fun1(){ return "pri_fun1"; }
// private, not accessible from extern
function pri_fun2(){ return "pri_fun2"; }
//static property
fe.sta_var1 = 0; //static property ....is never a good idea but...for folks!!!
//static method
fe.sta_fun1 = function(){return pri_fun2();}
//public not heritable
this.pub_fun1 = function(){return "pub_fun1";}
//public heritable
fe.prototype.pub_her_fun1 = function() { return "pub_her_fun1";}
//return fe;
}

var obj2 = new fe();
console.log("obj2 --> ",obj2);
console.log(obj2.pub_fun1());
console.log(fe.sta_fun1());


If I uncomment //return fe; the "node" say:
console.log(obj2.pub_fun1());
^



TypeError: obj2.pub_fun1 is not a function...
If I leave the comment all works as well....



A little bit of confusion about Function and Object in (again):




"Well, Javascript, or better ECMAScript, is an Object Based Language so.. Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript where an Object is a "bag" of properties and methods..."




thanks in advance



Ok...I'll try to be more precise.
I read "Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript where an Object is a "bag" of properties and methods..."
Hence a function is an object? Every function?
Take the function:



function fe(){
return 1;
};


and the following instructions:



console.log(fe);    // [Function: fe]
console.log(fe()); // 1
var vfe = new fe();
console.log(vfe); // fe {}


if I read well:
fe is a function that, being non primitive, is an "object" (what kind of object? Maybe somewhat complex type representation [Function: fe] called improperly object in a not OO way?)... but it becomes object in OO way of "bag" {} only after a new (vfe)...., but it can be also be invoked (fe()) and produce a value (1)...or can return itself or by default undefined...
Some functions could not be executed but only "instantiated"? and other function can contains functions which are classical function to execute to get a normal value but not to be instantiated???
Very, very strange behaviour...
Can I have an help in terms of naming, design and boundaries about this mess?
thanks again...










share|improve this question
















in web I read:




"Well, Javascript, or better ECMAScript, is an Object Based Language so..
Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript where an Object is a "bag" of properties and methods..."




and:




When a function is invoked with “new” keyword then the function is known as constructor function and returns a new instance. In such cases, the value of “this” refers to newly created instance.




Now, my code:



function fe(){
var i;
var j = 0;
return j;
};
process.stdout.write("fe --> "); console.log(fe); // [Function: fe]
process.stdout.write("fe() --> "); console.log(fe()); // 0

var vfe = new fe();
process.stdout.write("vfe --> " + vfe + " - "); console.log(vfe); [object Object] - fd {}




var fd = function(){
var i;
var j = 0;
};
process.stdout.write("fd --> "); console.log(fd); // [Function: fd]
process.stdout.write("fd() --> "); console.log(fd()); // undefined

var vfd = new fd();
process.stdout.write("vfd --> " + vfd + " - "); console.log(vfd); [object Object] - fd {}


In the first I have value returned and new return an object as the last case: I have an object {} and so I could append properties and methods



in an another case:



function fe(){
var i;
var j = 0;
return fe;
};
process.stdout.write("fe --> "); console.log(fe); // [Function: fe]
process.stdout.write("fe() --> "); console.log(fe()); // [Function: fe]

var vfe = new fe();
process.stdout.write("vfe --> "); console.log(vfe); // [Function: fe]


var fd = function(){
var i;
var j = 0;
return fd;
};
process.stdout.write("fd --> "); console.log(fd); // [Function: fd]
process.stdout.write("fd() --> "); console.log(fd()); // [Function: fd]

var vfd = new fd();
process.stdout.write("vfd --> "); console.log(vfd); // [Function: fd]


In this case I have a value or a Function returned that is all but an object....
Now:
id the "Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript where an Object is a "bag" of properties and methods..." not so true in all situation?



Another situation is the following:



function fe () {
var pri_var1;
// private, not accessible from extern
function pri_fun1(){ return "pri_fun1"; }
// private, not accessible from extern
function pri_fun2(){ return "pri_fun2"; }
//static property
fe.sta_var1 = 0; //static property ....is never a good idea but...for folks!!!
//static method
fe.sta_fun1 = function(){return pri_fun2();}
//public not heritable
this.pub_fun1 = function(){return "pub_fun1";}
//public heritable
fe.prototype.pub_her_fun1 = function() { return "pub_her_fun1";}
//return fe;
}

var obj2 = new fe();
console.log("obj2 --> ",obj2);
console.log(obj2.pub_fun1());
console.log(fe.sta_fun1());


If I uncomment //return fe; the "node" say:
console.log(obj2.pub_fun1());
^



TypeError: obj2.pub_fun1 is not a function...
If I leave the comment all works as well....



A little bit of confusion about Function and Object in (again):




"Well, Javascript, or better ECMAScript, is an Object Based Language so.. Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript where an Object is a "bag" of properties and methods..."




thanks in advance



Ok...I'll try to be more precise.
I read "Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript where an Object is a "bag" of properties and methods..."
Hence a function is an object? Every function?
Take the function:



function fe(){
return 1;
};


and the following instructions:



console.log(fe);    // [Function: fe]
console.log(fe()); // 1
var vfe = new fe();
console.log(vfe); // fe {}


if I read well:
fe is a function that, being non primitive, is an "object" (what kind of object? Maybe somewhat complex type representation [Function: fe] called improperly object in a not OO way?)... but it becomes object in OO way of "bag" {} only after a new (vfe)...., but it can be also be invoked (fe()) and produce a value (1)...or can return itself or by default undefined...
Some functions could not be executed but only "instantiated"? and other function can contains functions which are classical function to execute to get a normal value but not to be instantiated???
Very, very strange behaviour...
Can I have an help in terms of naming, design and boundaries about this mess?
thanks again...







javascript function object return new-operator






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 18 '18 at 16:18









georg

149k35200299




149k35200299










asked Nov 26 '18 at 16:19









user10529711user10529711

92




92








  • 1





    I don't understand. Could you please describe exactly what your question is?

    – zero298
    Nov 26 '18 at 16:23











  • return fe; overwrites the constructor function / instance behavior and instead assigns the function itself to obj2, regardless of the new. Don't return anything and you get an instance that behaves as expected. Even better: learn the new class stuff that was added to JavaScript.

    – Chris G
    Nov 26 '18 at 16:25













  • I've voting to close this as off-topic because it is too broad. You seem to have four separate questions here, none of them expressed very clearly.

    – Quentin
    Nov 26 '18 at 16:27











  • "what about functions" - they're objects as well (regardless of their kind).

    – Bergi
    Dec 15 '18 at 12:45














  • 1





    I don't understand. Could you please describe exactly what your question is?

    – zero298
    Nov 26 '18 at 16:23











  • return fe; overwrites the constructor function / instance behavior and instead assigns the function itself to obj2, regardless of the new. Don't return anything and you get an instance that behaves as expected. Even better: learn the new class stuff that was added to JavaScript.

    – Chris G
    Nov 26 '18 at 16:25













  • I've voting to close this as off-topic because it is too broad. You seem to have four separate questions here, none of them expressed very clearly.

    – Quentin
    Nov 26 '18 at 16:27











  • "what about functions" - they're objects as well (regardless of their kind).

    – Bergi
    Dec 15 '18 at 12:45








1




1





I don't understand. Could you please describe exactly what your question is?

– zero298
Nov 26 '18 at 16:23





I don't understand. Could you please describe exactly what your question is?

– zero298
Nov 26 '18 at 16:23













return fe; overwrites the constructor function / instance behavior and instead assigns the function itself to obj2, regardless of the new. Don't return anything and you get an instance that behaves as expected. Even better: learn the new class stuff that was added to JavaScript.

– Chris G
Nov 26 '18 at 16:25







return fe; overwrites the constructor function / instance behavior and instead assigns the function itself to obj2, regardless of the new. Don't return anything and you get an instance that behaves as expected. Even better: learn the new class stuff that was added to JavaScript.

– Chris G
Nov 26 '18 at 16:25















I've voting to close this as off-topic because it is too broad. You seem to have four separate questions here, none of them expressed very clearly.

– Quentin
Nov 26 '18 at 16:27





I've voting to close this as off-topic because it is too broad. You seem to have four separate questions here, none of them expressed very clearly.

– Quentin
Nov 26 '18 at 16:27













"what about functions" - they're objects as well (regardless of their kind).

– Bergi
Dec 15 '18 at 12:45





"what about functions" - they're objects as well (regardless of their kind).

– Bergi
Dec 15 '18 at 12:45












1 Answer
1






active

oldest

votes


















1














When you call a function as a constructor (i.e. new func()), JS takes these steps:




  • it creates a new object, let's call it newObject

  • it calls your function in a special way, so that this inside your function becomes newObject

  • the function runs, and returns a value, let's call it retVal

  • now JS looks into retVal. If it's nothing (that is, undefined) or a primitive value, then retVal is ignored (thrown away), and the result of whole new func() thing will be newObject

  • if, however, retVal is an object, JS does quite the opposite: newObject is discarded, and the value of new func() will be retVal


This explains your results, because in the first case you're returning a primitive (0) and in the second case, an object (fd, which is a function, and functions are objects).



Illustration:






function returnsPrimitive() {
this.x = 1
return 42
}

console.log(returnsPrimitive())
console.log(new returnsPrimitive())


function returnsObject() {
this.x = 1
return {foo:1}
}

console.log(returnsObject())
console.log(new returnsObject())








share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53485181%2fjavascript-function-object-new-a-little-bit-of-confusion%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    When you call a function as a constructor (i.e. new func()), JS takes these steps:




    • it creates a new object, let's call it newObject

    • it calls your function in a special way, so that this inside your function becomes newObject

    • the function runs, and returns a value, let's call it retVal

    • now JS looks into retVal. If it's nothing (that is, undefined) or a primitive value, then retVal is ignored (thrown away), and the result of whole new func() thing will be newObject

    • if, however, retVal is an object, JS does quite the opposite: newObject is discarded, and the value of new func() will be retVal


    This explains your results, because in the first case you're returning a primitive (0) and in the second case, an object (fd, which is a function, and functions are objects).



    Illustration:






    function returnsPrimitive() {
    this.x = 1
    return 42
    }

    console.log(returnsPrimitive())
    console.log(new returnsPrimitive())


    function returnsObject() {
    this.x = 1
    return {foo:1}
    }

    console.log(returnsObject())
    console.log(new returnsObject())








    share|improve this answer






























      1














      When you call a function as a constructor (i.e. new func()), JS takes these steps:




      • it creates a new object, let's call it newObject

      • it calls your function in a special way, so that this inside your function becomes newObject

      • the function runs, and returns a value, let's call it retVal

      • now JS looks into retVal. If it's nothing (that is, undefined) or a primitive value, then retVal is ignored (thrown away), and the result of whole new func() thing will be newObject

      • if, however, retVal is an object, JS does quite the opposite: newObject is discarded, and the value of new func() will be retVal


      This explains your results, because in the first case you're returning a primitive (0) and in the second case, an object (fd, which is a function, and functions are objects).



      Illustration:






      function returnsPrimitive() {
      this.x = 1
      return 42
      }

      console.log(returnsPrimitive())
      console.log(new returnsPrimitive())


      function returnsObject() {
      this.x = 1
      return {foo:1}
      }

      console.log(returnsObject())
      console.log(new returnsObject())








      share|improve this answer




























        1












        1








        1







        When you call a function as a constructor (i.e. new func()), JS takes these steps:




        • it creates a new object, let's call it newObject

        • it calls your function in a special way, so that this inside your function becomes newObject

        • the function runs, and returns a value, let's call it retVal

        • now JS looks into retVal. If it's nothing (that is, undefined) or a primitive value, then retVal is ignored (thrown away), and the result of whole new func() thing will be newObject

        • if, however, retVal is an object, JS does quite the opposite: newObject is discarded, and the value of new func() will be retVal


        This explains your results, because in the first case you're returning a primitive (0) and in the second case, an object (fd, which is a function, and functions are objects).



        Illustration:






        function returnsPrimitive() {
        this.x = 1
        return 42
        }

        console.log(returnsPrimitive())
        console.log(new returnsPrimitive())


        function returnsObject() {
        this.x = 1
        return {foo:1}
        }

        console.log(returnsObject())
        console.log(new returnsObject())








        share|improve this answer















        When you call a function as a constructor (i.e. new func()), JS takes these steps:




        • it creates a new object, let's call it newObject

        • it calls your function in a special way, so that this inside your function becomes newObject

        • the function runs, and returns a value, let's call it retVal

        • now JS looks into retVal. If it's nothing (that is, undefined) or a primitive value, then retVal is ignored (thrown away), and the result of whole new func() thing will be newObject

        • if, however, retVal is an object, JS does quite the opposite: newObject is discarded, and the value of new func() will be retVal


        This explains your results, because in the first case you're returning a primitive (0) and in the second case, an object (fd, which is a function, and functions are objects).



        Illustration:






        function returnsPrimitive() {
        this.x = 1
        return 42
        }

        console.log(returnsPrimitive())
        console.log(new returnsPrimitive())


        function returnsObject() {
        this.x = 1
        return {foo:1}
        }

        console.log(returnsObject())
        console.log(new returnsObject())








        function returnsPrimitive() {
        this.x = 1
        return 42
        }

        console.log(returnsPrimitive())
        console.log(new returnsPrimitive())


        function returnsObject() {
        this.x = 1
        return {foo:1}
        }

        console.log(returnsObject())
        console.log(new returnsObject())





        function returnsPrimitive() {
        this.x = 1
        return 42
        }

        console.log(returnsPrimitive())
        console.log(new returnsPrimitive())


        function returnsObject() {
        this.x = 1
        return {foo:1}
        }

        console.log(returnsObject())
        console.log(new returnsObject())






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Dec 15 '18 at 12:37

























        answered Nov 26 '18 at 17:17









        georggeorg

        149k35200299




        149k35200299
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53485181%2fjavascript-function-object-new-a-little-bit-of-confusion%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Contact image not getting when fetch all contact list from iPhone by CNContact

            count number of partitions of a set with n elements into k subsets

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks