简体   繁体   English

JavaScript中某个方法的存在:检查真实性是否足够?

[英]Existence of a method in JavaScript: Checking for truthy sufficient?

If I like to test if an object has a specific method: Would the following code work reliable? 如果我想测试对象是否具有特定方法:以下代码是否可靠?

const obj = {
  add(a, b) {
    return a + b
  }
}

if (obj.add) {
    console.log(obj.add(9, 3));
}

if (obj.sub) {
    console.log(obj.sub(8, 2));
}

Or would it potentially fail? 还是可能失败? If so: For what reason? 如果是这样:出于什么原因?

And if it isn't sufficient: What should I use instead? 如果还不够的话,我应该怎么用呢?

Since you want to call the method, you should check to see it's actually a method first. 由于要调用该方法,因此应首先检查它实际上是一个方法。 If it's a non-function property, what you're doing will result in a TypeError. 如果它是非函数属性,则您执行的操作将导致TypeError。

 const obj = { add: true } if (obj.add) { console.log(obj.add(9, 3)); } if (obj.sub) { console.log(obj.sub(8, 2)); } 

So: 所以:

 const obj = { add(a, b) { return a + b }, badProp: true } const verify = arg => typeof arg === 'function'; if (verify(obj.add)) { console.log(obj.add(9, 3)); } if (verify(obj.sub)) { console.log(obj.sub(8, 2)); } if (verify(obj.badProp)) { obj.badProp(); } 

typeof() is a way to check weather a var is a function or anything else. typeof()是一种检查天气的方法,var是一个函数或其他任何东西。

if (typeof obj.add === 'function') {
    console.log(obj.add(9, 3));
}

Instead if checking for just name. 相反,如果仅检查名称。 I would suggest checking type too. 我也建议检查类型。 Refer below code for same 请参考以下代码

const obj = {
  add(a, b) {
    return a + b
  }
}
if (typeof obj.add === "function") { 
    console.log(obj.add(9, 3));
}

if (typeof obj.sub === "function") {
    console.log(obj.sub(8, 2));
}

You can try like this .Check if object key is a function, 您可以这样尝试。检查object key是否为函数,

 const obj = { add:function (a, b) { return a + b }, sub:function (a, b) { return a - b } } if (typeof obj.add === 'function') { console.log(obj.add(9, 3)); } if (typeof obj.sub === 'function') { console.log(obj.sub(8, 2)); } 

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

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