开发者

Why "return o" in this simple example?

开发者 https://www.devze.com 2023-02-18 17:41 出处:网络
<html> <body> <script type=\"text/javascript\"> function createPerson (name){ var o = new Objec开发者_运维技巧t();
<html>
<body>

<script type="text/javascript">

function createPerson (name){
var o = new Objec开发者_运维技巧t();
o.name = name;

return o;
};
var person1 = createPerson ("Nicholas");
alert(person1.name);
</script>

</body>
</html>

Why do we have to

return o

? What does "return" mean?


If you don't know what return means then I suggest reading just about any book on procedural, functional or object oriented programming before you write anything in any language and get into trouble.

You can start from Eloquent JavaScript: A Modern Introduction to Programming by Marijn Haverbeke, available online.


The return keyword is the basic mechanism of getting a result out of a function. It sounds like you don't understand the basics. Have a read over return @ MDC. Another helpful MDC page: Functions!


Ok. This is like a walk-through of the code. START reading from Line 6.

1: function createPerson (name){ //name will now be "Nicholas"
2: var o = new Object();//created a new object, store it in o
3: o.name = name;//added a name property assign name to it (would be Nicholas)
4: return o; //<<return o BACK to line 6.
5: };
6: var person1 = createPerson ("Nicholas");//<<goes to Line 1.
//BACK here person1 have the value of o
7: alert(person1.name); //In line 3 we did o.name = "Nicholas"
//since person1 is equal to o this will popup an alert saying Nicholas.

I more or less simplified it being less strict/formal with the words I used.


return is a JavaScript keyword that causes the function it's placed in to exit with the specified value (called the "return value").

In this case, it causes the createPerson() function to come to an end, returning the o object to the caller of the function.

The o object, once returned from createPerson(), then gets assigned to the person1 variable.

So the net result is that control flow starts here

var person1 = createPerson ("Nicholas");

then jumps into the createPerson() function, which creates a new object representing a person with the name "Nicholas", then returns it, which brings the execution back to that line, with person1 getting the newly created person that the function returned.

0

精彩评论

暂无评论...
验证码 换一张
取 消