JavaScript: explain the return statement in the constructor

0 like 0 dislike
3 views
Please explain what is the difference between the code:

var Test = (function () {
return (function () {
this.qqq = 'a';
});
})();

alert(new Test().qqq);


and

var Test = (function () {
return (function () {
return ({ qqq : 'a' });
});
})();
alert(new Test().qqq);


In both variants displays "a". Why in the first case — clear. The first function creates a closure, which can hold "static" variables. Second — the actual constructor and the constructor defines the object. But why the second?

Thank you.
by | 3 views

2 Answers

0 like 0 dislike
For ease of understanding, the examples can be reduced to the following.
First: function Test() { this.qqq = a; }
Second: function Test() { return {qqq: 'a'}; }
\r
We now turn to the specification of ECMA-262, paragraph 13.2.2. [[Construct]]
\r
When the [[Construct]] property for a Function object F is called, the following steps are taken:
1. Create a new native ECMAscript object.
2. Set the [[Class]] property of Result(1) to "Object".
3. Get the value of the prototype property of the F.
4. If Result(3) is an object, set the [[Prototype]] property of Result(1) to Result(3).
5. If Result(3) is not an object, set the [[Prototype]] property of Result(1) to the original Object prototype object as described in 15.2.3.1.
6. Invoke the [[Call]] property of F, providing Result(1) as the this value and providing the argument list passed into [[Construct]] as the argument values.
7. If Type(Result(6)) is Object then return Result(6).
8. Return Result(1).
\r
The clue lies in the last two lines: if the function returns an object then the result of the work of the designer is considered to be this object if the function returns something else (or returns nothing), the result of the work of the constructor is the new object that you created in step 1.
by
0 like 0 dislike
what indiski code? how do I know what exactly you do not understand?
\r
the second example uses json
by

Related questions

0 like 0 dislike
4 answers
0 like 0 dislike
3 answers
asked Apr 9, 2019 by RuComMarket
0 like 0 dislike
2 answers
0 like 0 dislike
1 answer
0 like 0 dislike
2 answers
110,608 questions
257,186 answers
0 comments
28,872 users