if I have function like this:
function Apple(){
this.color = "green";
return this;
}
When creating object like this:
var my_obj = new Apple();
is that line return this; necessary and/or is it valid by language reference?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, returning
thisis not necessary, but it is valid. If the returned value is an object,newwill return that object instead of the newly created object.See points 11.2.2 and 13.2.2 of ECMAScript 5:
The new operator calls the internal [[Construct]] method on the constructor (usually a function):
The [[Construct]] internal method of functions is described in point 13.2.2: