Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return statement in a function as class

Tags:

javascript

I am confused about the return statement in a function that serves as a class. See the example code below:

<html>
<body>

<script type="text/javascript">
function test() {
    this.abc = 'def';
    return 3;
}

var mytest = new test(); 

document.write(mytest + ', ' + (typeof mytest) + ', ' + mytest.abc);

</script>

</body>
</html>

The code out put: [object Object], object, def.

Here is my question. I wrote 'return 3' in the test() function. Is this statement ignored when 'new test()' is called?

Thanks.

like image 532
Kai Avatar asked Oct 14 '25 03:10

Kai


2 Answers

When you call a function with new, you're invoking it as a constructor which automatically returns the new object it constructs.

Your return 3; statement is ignored. What is returned is effectively:

{ abc:'def' }

...with an implicit reference to a prototype object, which in your example doesn't have any enumerable properties because you haven't given it any.

If you did:

mytest instanceof test;

...it would evaluate to true.

If you did:

function test() {
    this.abc = 'def';
}
test.prototype.ghi = 'jkl';

var mytest = new test(); 

...you could then do:

mytest.ghi;

...which would give you the value 'jkl'.

like image 164
user113716 Avatar answered Oct 16 '25 15:10

user113716


When you use the new operator, you're using the function as a constructor, in that case for the return value:

  • if it's not an object, it is ignored (like in your example)
  • if it is an object, the object returned becomes the result of the whole new expression

So if you were to write

Test = function(arg) {
    this.a = 1;
    return arg;
}

var t1 = new Test(10);
var t2 = new Test({b: 2}); 
console.log(t1, t2)
// output:
//   Test {a:1}   Object {b: 2}
like image 21
aljgom Avatar answered Oct 16 '25 16:10

aljgom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!