[英]Javascript: Passing large objects or strings between function considered a bad practice
Is it considered a bad practice to pass around a large string or object (lets say from an ajax response) between functions? 在函数之间传递一个大字符串或对象(比如从ajax响应中)被认为是一种不好的做法吗? Would it be beneficial in any way save the response in a variable and keep reusing that variable?
以任何方式保存变量中的响应并继续重用该变量是否有益?
So in the code it would be something like this: 所以在代码中它将是这样的:
var response;
$.post(url, function(resp){
response = resp;
})
function doSomething() {
// do something with the response here
}
vs VS
$.post(url, function(resp){
doSomething(resp);
})
function doSomething(resp) {
// do something with the resp here
}
Assume resp
is a large object or string and it can be passed around between multiple functions. 假设
resp
是一个大对象或字符串,它可以在多个函数之间传递。
Objects and strings in javascript are passed by reference. javascript中的对象和字符串通过引用传递。 (Technically by value of reference, which means reassigning with
=
the variable inside the function won't affect the variable outside the function, but that's besides the point for this question.) (从技术上讲,通过引用值,这意味着重新分配
=
函数内部的变量不会影响函数外部的变量,但除了这个问题的点之外。)
That means that it is not expensive to pass them to functions because no copy is made. 这意味着将它们传递给函数并不昂贵,因为没有复制。 All that is passed to the function is just a pointer to the original object and this is efficient.
传递给函数的所有内容只是指向原始对象的指针,这是有效的。
You need to also realize that your first scheme does not even work properly: 您还需要意识到您的第一个方案甚至无法正常工作:
var response;
$.post(url, function(resp){
response = resp;
})
function doSomething() {
// do something with the response here
}
because of the timing of things, you don't know when to call doSomething()
. 因为时间的关系,你不知道何时调用
doSomething()
。 $.post()
as you show it is asynchronous and thus you have no idea when it is actually done. $.post()
因为你显示它是异步的,因此你不知道它何时实际完成。 The resp
value in your code MUST be used from the completion function. 代码中的
resp
值必须在完成函数中使用。 You must either use it in the completion function or call something from the completion function and pass resp
to it (like your second example). 您必须在完成函数中使用它,或者从完成函数调用一些东西并将
resp
传递给它(就像您的第二个示例)。 Only then will you get the timing correct for when that data is available. 只有这样,您才能获得有关数据可用时的正确时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.