Javascript,我可以传递对当前对象的引用以在对象字面量定义中运行吗?
早上好,
我有一个以选项哈希作为参数的函数,我可以在对象字面量定义中调用该函数吗?像这样
function dataCallback(opts) {
var rowSelector = opts['id'] + ' .gridContent';
var liSelector = opts['id'] + ' li';
return function(args) { //do something with opts...
return;
}
//omitted...
}
var obj = { x : {id = '#someId1', callback: dataCallback(//what can I pass here? this? x? obj.x? nothing seems to work...)}
, y : {id = '#someId2', callback: dataCallback(///???, this? y? obj.y?)} };
我希望我的问题有意义。也许我在标题中措辞不正确。无论如何,如果有人能在这里纠正我,我将非常感激。感谢您提供任何提示或技巧。
干杯,
〜ck在圣地亚哥
Good Morning,
I have a function that takes an options hash as it's parameter, can I call that function inside an object literal definition? Like this
function dataCallback(opts) {
var rowSelector = opts['id'] + ' .gridContent';
var liSelector = opts['id'] + ' li';
return function(args) { //do something with opts...
return;
}
//omitted...
}
var obj = { x : {id = '#someId1', callback: dataCallback(//what can I pass here? this? x? obj.x? nothing seems to work...)}
, y : {id = '#someId2', callback: dataCallback(///???, this? y? obj.y?)} };
I hope my question makes sense. Perhaps I worded it incorrectly in the title. Anyways, if someone can straighten me out here I would truly appreciate it. Thanks for any tips or tricks.
Cheers,
~ck in San Diego
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我了解,您想要将函数的返回值分配给对象的属性,并将对象本身传递给函数。这是正确的吗?
你不能一次性完成这件事。您必须分开步骤:
From what I understood is that you want to assign the return value of the function to a property of the object and passing the object itself to the function. Is this correct?
You cannot do this in one go. You have to separate the steps:
尝试一下:
为了执行 dataCallback(this) ,您需要将其放入匿名 fn 中,否则 this 不引用该对象,它引用全局 DOMWindow
try this:
in order to do
dataCallback(this)
you need to put it in an anon fn or else this does not refer to the object, it refers to the globalDOMWindow
是的,没有任何作用,因为 JSON 不可自引用,现在只有 Firefox 支持 JSON 中的 Sharp Variable,因此您可以这样写:
请注意,Sharp Variable 仅受 Firefox 的某些版本支持,并且将来可能会被删除,所以使用时要慎重考虑。
Sharp Variable 中的语法非常严格,因此您应该编写“x:#1={”,每个字符中没有任何多余空格。
Sharp变量参考:https://developer.mozilla.org/en/Sharp_variables_in_JavaScript
Yes, nothing works, because JSON is not self-referenceable, only Firefox now supports Sharp Variable in JSON so that you may write like this:
Note that Sharp Variable is only supported by some versoin of Firefox and will possibily be removed at future point, so use it at consideration.
Syntax in Sharp Variable is extremely strict so that you should write "x:#1={" without any extra space in each character.
For reference of Sharp Variable: https://developer.mozilla.org/en/Sharp_variables_in_JavaScript