JavaScript 中指向变量的指针
有没有办法在 JavaScript 中创建\返回一个指向变量的指针?
就像,在 PHP 中:
function func() {
.....
return &$result;
}
我有一个 JS 函数,例如:
function(...) {
x=document.getElements..... //x is HTML tag
if (x.localName=='input') return x.value //String variable
else if (x.localName=='textarea') return x.innerHTML //String variable
}
使用这个函数,我可以从 x 获取数据的副本,但不能更改源。
我也希望有机会改变它。
谢谢
Is there any way to create\return a pointer to variable in JavaScript ?
like, in PHP :
function func() {
.....
return &$result;
}
I have a JS function like:
function(...) {
x=document.getElements..... //x is HTML tag
if (x.localName=='input') return x.value //String variable
else if (x.localName=='textarea') return x.innerHTML //String variable
}
Using this function, I can get a copy of the data from x, but not to change the source.
I want possibility to change it too.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,您不能返回指向字符串的指针。在 Javascript 中,对象通过引用自动分配和传递,并且原语被复制。因此,如果您
return x;
,那么您可以修改x.innerHTML
,但如果您返回x.innerHTML
,则字符串将被复制。No, you can't return a pointer to a string. In Javascript Objects are assigned and passed by reference automatically, and primitives are copied. So if you
return x;
then you can modifyx.innerHTML
, but if you returnx.innerHTML
the string will be copied.Hej Dani-Br
您可以执行类似的操作,
以便调用者可以设置并获取该值。
附:使用 var 声明局部变量
GL
Hej Dani-Br
you can do something like this
so that the caller can set and get the value.
ps. use var to declare local vars
GL
基本类型按值传递。对象通过引用传递。我猜 x.innerHTML 是一个字符串,所以它是按值传递的。
看一下这段代码,它显示了通过引用传递对象:
Primitive types are passed by value. Objects are passed by reference. I guess x.innerHTML is a string, so it is passed by value.
Take a look at this piece of code, it shows you passing objects by reference:
这可能不完全是您正在寻找的,但尚未提出的一件事是内部函数可以访问其外部函数的变量:
此外,您可以使用闭包来保存外部函数变量的状态:
This might not be exactly what you are looking for but one thing that hasn't been brought up yet is that inner functions can access the variables of their outer functions:
Additionally you can use a closure to save the state of an outer functions variables: