当关联函数中的原型值丢失时,函数中断
function Breaks when prototyped values in an associated function are missing
如何检查donald duck在"function in TheForest(object)"中是否有名称,如果它没有显示警报("找不到名称"),然后继续显示john person的警报?
function Duck() {}
Duck.prototype.quack = function() {alert('Quaaaaaack!');};
Duck.prototype.feathers = function() {alert('The duck has white and gray feathers.');};
//Duck.prototype.name = function() {alert('Donald Duck');};
function Person() {}
Person.prototype.quack = function() {alert('The person imitates a duck.');};
Person.prototype.feathers = function() {alert('The person takes a feather from the ground and shows it.');};
Person.prototype.name = function() {alert('Rick James');};
function inTheForest(object) {
object.quack();
object.feathers();
object.name();
}
function game() {
var donald = new Duck();
var john = new Person();
inTheForest(donald);
inTheForest(john);
}
game();
您可以通过typeof
进行检查
像这个
if(typeof object.name === "undefined"){
console.log("no name found")
}
试试这个。
function inTheForest(object) {
object.quack();
object.feathers();
if(typeof object.name==='function'){
object.name();
}else{
alert('no name found');
}
}
事实上,在调用该属性之前,您应该始终检查该属性是否为函数(如果您不确定该属性是否存在)。因此,您可能也想将其用于quack
和feathers
。
一个简单的if语句,如果object.name
存在
object.name()? object.name(): alert("no name found");
您可以简单地执行以下操作:
if (object.quack) object.quack();
if (object.feathers) object.feathers();
if (object.name) object.name();
您可能还想介绍else
语句:
if (object.quack)
object.quack()
else
console.log('Warning! Every object should be able to quack. Not found for ' + object);
if (object.feathers) object.feathers();
if (object.name) object.name();
这是因为不存在的函数被评估为undefined
,这是falsy;而存在的函数是truthy。
相关文章:
- 递归函数中断
- 从jquery foreach内部中断函数
- JavaScript 函数在 IE9 中随机中断
- Angularjs 与 coffeescript 函数表达式中断
- Javascript:变量中断函数
- return语句在JavaScript中使用而不中断函数
- 调用加载的顺序函数会意外中断代码
- 从匿名函数中中断for循环
- 清除文本区域会中断其他JS函数
- 如何在返回值(Js)时不中断函数/循环
- 进度条函数在一次调用后中断
- 一个函数在另一个函数上中断.可能吗
- 中断 JQuery 设置超时函数
- 在 ASP.NET 页面中内联编码 SVG 会导致 SVG JavaScript 创建 SVGPoint();函数中断
- 从调用/子函数退出/中断主函数
- 如何从递归函数中断和返回
- 如何在满足条件时中断CasperJS的重复函数
- JavaScript 函数的执行可以被中断吗?
- 当关联函数中的原型值丢失时,函数中断
- 为什么Javascript'的日期()函数中断我的生日在Safari