[英]How can I call a possibly-non-existent method, without errors, in one line in JavaScript?
I was writing a program that uses javascript and creates inheritance in a way. 我正在编写一个使用javascript并以某种方式创建继承的程序。
If the user types in: 如果用户键入:
x.isSingleLine()
and it does not exist, it crashes Javascript. 并且它不存在,它使Javascript崩溃。 I was hoping there was a way to do something like:
我希望有一种方法可以执行以下操作:
x.isSingleLine() || "Doesnt Exist";
to in a way have it do a soft error or some sort of alert. 以某种方式使它执行软错误或某种警报。 I didnt want to have to encapsulate the object in a try-catch block.
我不想将对象封装在try-catch块中。
Is there a way this can be accomplished? 有没有办法可以做到这一点?
In the statement: x.isSingleLine() || 在语句中: x.isSingleLine()|| "Doesnt Exist";
“不存在”; it will crash and not do the OR part, so this is not the answer apparently.
它将崩溃,并且不执行“或”部分,因此显然这不是答案。
How about that? 那个怎么样?
x.isSingleLine ? x.isSingleLine() : console.log("Doesnt Exist");
Edit: As suggested by @FelixKling if there's a chance that isSingleLine
exists but is not a function you should instead use: 编辑:如@FelixKling所建议,如果
isSingleLine
存在但不是函数,则应改用:
(x.isSingleLine && x.isSingleLine instanceof Function) ? x.isSingleLine() : console.log("Doesnt Exist");
您需要在调用之前检查它是否存在。
var result = x.isSingleLine ? x.isSingleLine() : "Doesn't Exist";
As far as I know from the top of my head, you can use a try-catch block for that: 据我了解到的,您可以使用try-catch块:
try {
x.isSingleLine();
} catch (e) {
// Something happened
alert("isSingleLine didn't quite work out.");
}
Play around with it in this fiddle 在这个小提琴中玩耍
Update I now noticed that you don't want to encapsulate in a try-catch block. 更新我现在注意到,您不想封装在try-catch块中。 Using a try-catch block though can even handle errors inside the isSingleLine() method as shown in the updated fiddle .
不过,使用try-catch块甚至可以处理isSingleLine()方法内部的错误,如更新的fiddle所示。
(x.isSingleLine || function(){
console.log("Doesn't Exist");
})()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.