当关联函数中的原型值丢失时,函数中断

function Breaks when prototyped values in an associated function are missing

本文关键字:函数 中断 原型 关联      更新时间:2023-09-26

如何检查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');
  }
}

事实上,在调用该属性之前,您应该始终检查该属性是否为函数(如果您不确定该属性是否存在)。因此,您可能也想将其用于quackfeathers

一个简单的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