简体   繁体   English

如何使用变量引用类

[英]How to refer to class using variable

If I have this object: 如果我有这个对象:

var myclass = {

  foo: {
    bar: function(var) {}
  },
  some: {
    bar: function(var) {}
  }
}

and I want to call the bar function depending on a variable that defines the parent level of the object like this: 我想根据定义对象父级的变量来调用bar函数,如下所示:

var part = "some";
myclass.part.bar(var);

How can I do? 我能怎么做?

You can do it using array access notation: 您可以使用数组访问符号来实现:

myclass[part].bar(var);

JavaScript objects are like associative arrays, and you can use a property name to either set or get the property's value, you can even create new properties with this syntax. JavaScript对象就像关联数组一样,您可以使用属性名称来设置或获取属性的值,甚至可以使用此语法创建新属性。

For example: 例如:

var obj = { a : 1 };
console.log(obj["a"]); // 1
obj["b"] = 2; // this creates a property called b and assigns 2 as the value
console.log(obj["b"]); // 2

You can keep a reference to a function as a variable, which is a little cleaner than a string. 您可以将对函数的引用保留为变量,它比字符串干净一点。

var func = myclass.foo.bar;//or myclass.some.bar
...
func.call(myclass, var);

Or keep a reference to the part: 或保留对零件的引用:

var part = myclass.foo;//or myclass.some
part.bar.call(myclass, var);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM