简体   繁体   English

为什么在javascript函数中需要返回?

[英]Why return is required in javascript function?

When i executed following JavaScript code, i got undefined 当我执行以下JavaScript代码时,我undefined

var ns=new String('hello world');
String.prototype.capitalAll=function(){
                                 this.toUpperCase()
                                       };
alert(ns.capitalAll()); // undefined

But, when i add return , it returns a value 但是,当我添加return ,它返回一个值

var ns=new String('hello world');
String.prototype.capitalAll=function(){
                                 return this.toUpperCase() // added return
                                       };
alert(ns.capitalAll()); // HELLO WORLD

Why return is required here and in end of every function. 为什么在这里以及每个函数的结尾都需要return I have seen use of return in many javascript frameworks. 我已经在许多javascript框架中看到了return用法。

How else would you return data from a function call? 您还如何通过函数调用返回数据?

Functions like Array.prototype.shift() are transformative, in that they modify the array. 诸如Array.prototype.shift()类的函数是可转换的,因为它们可以修改数组。 Internally, they do something like this[this.length] = newvalue and actually modify this in some way. 在内部,他们这样做this[this.length] = newvalue和实际修改this以某种方式。

But most functions are not transformative, they return the result. 但是大多数函数不是可转换的,它们返回结果。

return allows you to define what a function passes back when its called. return允许您定义函数在调用时返回的内容。

Its not required to have a return value, you can have a function that returns nothing, it just modifies other variables or prints something and then continues. 它不需要具有返回值,您可以具有不返回任何内容的函数,它仅修改其他变量或打印某些内容然后继续。

undefined is returned when you don't specifically specify another value to be returned 当您没有明确指定要返回的另一个值时,返回undefined

What toUpperCase does: toUpperCase的作用:

The thing is that toUpperCase doesn't modify "this" in the first place. 关键是toUpperCase首先不会修改“ this”。 That is a function that returns a value. 那是一个返回值的函数。

Some methods modify the object they are called on (they modify "this").. and in those cases you could write the function like you had it. 有些方法修改了调用它们的对象(它们修改了“ this”)。在这种情况下,您可以像编写函数那样编写函数。 In this case though, you need to use the "return" value. 但是,在这种情况下,您需要使用“返回”值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM