简体   繁体   中英

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.

 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.

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,

 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)); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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