Reputation: 5674
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?
Upvotes: 0
Views: 42
Reputation: 1
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));
}
Upvotes: 1
Reputation: 4097
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();
}
Upvotes: 2
Reputation: 516
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));
}
Upvotes: 1
Reputation: 646
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));
}
Upvotes: 1