A
A
Alex2010-10-09 02:08:51
JavaScript
Alex, 2010-10-09 02:08:51

JavaScript: explain return in constructor

Please explain what is the difference between the code: and In both options, “a” is displayed. Why in the first case is understandable. The first function creates a closure in which you can put "static" variables. The second is the constructor itself, and the object is set in the constructor. But why in the second? Thank you.

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

alert(new Test().qqq);



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



Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
apangin, 2010-10-09
@apangin

For ease of understanding, the examples can be reduced to the following.
First: function Test() { this.qqq = a; }
Second: function Test() { return {qqq: 'a'}; }
Now let's turn to the ECMA-262 specification, clause 13.2.2.
When the property for a Function object F is called, the following steps are taken:
1. Create a new native ECMAscript object.
2. Set the 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 property of Result(1) to Result(3).
5. If Result(3) is not an object, set the property of Result(1) to the original Object prototype object as described in 15.2.3.1.
6. Invoke the property of F, providing Result(1) as the this value and providing the argument list passed into as the argument values.
7. If Type(Result(6)) is Object then return Result(6).
8. Return Result(1).
The answer lies in the last two lines: if the function returns an object, then this object is considered the result of the constructor's work, but if the function returns something else (or does not return anything), the result of the constructor's work is the new object created in step 1.

O
ojiga, 2010-10-09
@ojiga

what is hindu code? How do I know what exactly you don't understand?
second example uses json

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question