我的理解:在 Javascript 中,对象和数组作为引用而不是函数参数的值传递。 jQuery 组是一个对象,因此应作为引用传递。
但是我在下面的测试脚本中发现发生了一些奇怪的事情;除非包裹在另一个对象中,否则 jQuery 组的行为就像一个值而不是一个引用......任何人都可以解释这一点吗?
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<script>
function test(arg){
arg = arg.add($('<span/>'))
console.log(arg);
};
ele = $('<div/>');
test(ele); // div + span in the group as expected
console.log(ele); // only the div - the 'arg' param in function was a copy
function test2(arg){
arg.a = arg.a.add($('<span/>'));
console.log(arg.a);
};
obj = {a:ele};
test2(obj); // div + span in the group as expected
console.log(obj.a); // both in the group - arg acted like a reference!
</script>
</body>
</html>
最佳答案
这是 .add() 的一个“特征”方法。它不修改原始 jQuery 对象,而是返回一个具有附加值的新对象。
鉴于您的第一个示例,您需要返回 arg变量并覆盖 ele .
function test(arg){
arg = arg.add($('<span/>'))
console.log(arg);
return arg; // return the new jQuery object stored in "arg"
};
ele = $('<div/>');
ele = test(ele); // overwrite the original "ele" with the returned value
console.log(ele);
编辑:再举一个例子,使用您的代码,但带有 .push()它修改了原始对象,您将在 ele 中看到更新的正确值.
function test(arg){
arg = arg.push($('<span/>')[0])
console.log(arg); // Because .push() is being used, "arg" will reference
// the new length of the array.
};
ele = $('<div/>');
test(ele);
console.log(ele); // Will reference jQuery object with both elements
编辑:最后一个插图。因为.add()返回一个新对象,您可以像这样更新两个变量以指向相同的值:
ele = arg = arg.add($('<span/>'));
现在代替 ele引用原文,和arg引用创建的新对象,两个变量都持有对内存中同一对象的引用。
关于javascript - 作为参数传递给函数的 jQuery 对象是值副本而不是引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3709753/
exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby中使用两个参数异步运行exe吗?我已经尝试过ruby命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何rubygems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除
我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere
我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"
我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)
两者都可以defsetup(options={})options.reverse_merge:size=>25,:velocity=>10end和defsetup(options={}){:size=>25,:velocity=>10}.merge(options)end在方法的参数中分配默认值。问题是:哪个更好?您更愿意使用哪一个?在性能、代码可读性或其他方面有什么不同吗?编辑:我无意中添加了bang(!)...并不是要询问nobang方法与bang方法之间的区别 最佳答案 我倾向于使用reverse_merge方法:option
我正在尝试用ruby中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了
我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin
我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano
rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送