获取对象的所有方法和属性

get all methods and properties of an object

本文关键字:属性 有方法 取对象 获取      更新时间:2023-09-26

如果我使用(在文本框架上):

b.selection().fit(FitOptions.frameToContent);

然后它按预期工作,这意味着所选对象具有适合方法。

如果我使用:

for (var property in b.selection()) {
    b.println(property);
}

在同一选择上,它不会打印适合方法。

如果我使用这个:

function getMethods(obj) {
  var result = [];
  for (var id in obj) {
    try {
      if (typeof(obj[id]) == "function") {
        result.push(id + ": " + obj[id].toString());
      }
    } catch (err) {
      result.push(id + ": inaccessible");
    }
  }
  return result;
}

b.println(getMethods(b.selection()));

那我也没法。我真的很想知道所选对象的所有方法和属性。那么我该如何获得它们呢?

尝试obj.reflect.methods获取所有方法

当方法fit()存在并且没有在for-in-loop中发光时,它是一个不可枚举的属性。

有多种方法可以访问对象的属性:

var obj = b.selection();
for (var p in obj) {
    console.log(p); // --> all enumerable properties of obj AND its prototype
}
Object.keys(obj).forEach(function(p) {
    console.log(p); // --> all enumerable OWN properties of obj, NOT of its prototype
});
Object.getOwnPropertyNames(obj).forEach(function(p) {
    console.log(p); // all enumerable AND non-enumerable OWN properties of obj, NOT of its prototype
});

如果你在这种方式之一上找不到.fit(),它不是可枚举的,也不是 obj 的 OWN 属性,而是位于 obj 原型中的某个地方。然后你可以做:

var prot = Object.getPrototypeOf(obj);
Object.getOwnPropertyNames(prot).forEach(function(pp) {
    console.log(pp); // --> all enumerable AND non-enumerable properties of obj's prototype
});

通常对象具有更长的原型链,并且属性位于其更深的位置。然后,您只需根据需要重复最后一个代码片段:

var prot2 = Object.getPrototypeOf(prot);
Object.getOwnPropertyNames(prot2).forEach( /*...*/ );

要使其完整:假设您在 obj 的原型prot上发现了.fit。然后你可以检查它:

console.log(Object.getOwnPropertyDescriptor(prot.fit));

这将输出一个对象,该对象显示prot.fit的值以及它是否可枚举、可写和可配置。 Object.methods和更多 在这里找到。

或者只使用 b.inspect(obj) .以递归方式将对象的所有属性和值打印到控制台。请参阅 http://basiljs.ch/reference/#inspect