tro*_*skn 87
当然:
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;
}
Run Code Online (Sandbox Code Playgroud)
使用它:
alert(getMethods(document).join("\n"));
Run Code Online (Sandbox Code Playgroud)
mrd*_*ded 18
如果您只想查看对象内部的内容,可以打印所有对象的键.其中一些可以是变量,一些是方法.
该方法不是很准确,但它非常快:
console.log(Object.keys(obj));
Run Code Online (Sandbox Code Playgroud)
这是一个ES6示例。
// Get the Object's methods names:
function getMethodsNames(obj = this) {
return Object.keys(obj)
.filter((key) => typeof obj[key] === 'function');
}
// Get the Object's methods (functions):
function getMethods(obj = this) {
return Object.keys(obj)
.filter((key) => typeof obj[key] === 'function')
.map((key) => obj[key]);
}
Run Code Online (Sandbox Code Playgroud)
obj = this是一个 ES6 默认参数,你可以传入一个 Object 或者它会默认为this.
Object.keys返回Object自己的可枚举属性的数组。在windowObject 上,它将返回[..., 'localStorage', ...'location']。
(param) => ... 是一个 ES6 箭头函数,它是
function(param) {
return ...
}
Run Code Online (Sandbox Code Playgroud)
带有隐式回报。
Array.filter创建一个包含所有通过测试的元素的新数组 ( typeof obj[key] === 'function')。
Array.map创建一个新数组,其结果是对该数组中的每个元素调用提供的函数(返回obj[key])。