似乎我只能为此创建一个全局变量,但这才是理想的选择。我想将变量传递给具有引用功能键的对象。在我所引用的函数中,我想设置该变量或在调用该函数的函数中定义的变量,并将其传递回去:
var methodHandler = {
'a-key': function () {
aVariable = document.getElementById('a-container');
}
}
function sample() {
var aVariable;
methodHandler['a-key']();
console.log(aVariable);
}
sample();
您应该使用this
元素。this
当在对象的函数内部调用该元素时,该元素被称为对象本身,因此这样做this.foo = 1
实际上会在您的对象中创建一个名为foo的属性,而该属性的值为1。
这是正确的代码形式:
var methodHandler = {
'a-key': function () {
this.aVariable = document.getElementById('a-container');
return this.aVariable;
}
}
function sample() {
// You can do this:
methodHandler['a-key']();
console.log(methodHandler['aVariable']);
// Or you can do this instead:
console.log(methodHandler['a-key']());
}
sample();
调用时,methodHandler['a-key']()
该属性aVariable
将在对象中设置,因此,如果您记录该对象,则会看到以下内容:
console.log(methodHandler);
> Object {a-key: function, aVariable: div#a-container}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句