javascript - 当关联函数中的原型(prototype)值丢失时,函数会中断

标签 javascript

如何检查唐老鸭在“function inTheForest(object)”中是否有名称,并且如果它不显示警报(“未找到名称”),然后继续显示约翰人的警报?

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

关于javascript - 当关联函数中的原型(prototype)值丢失时,函数会中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34430228/

相关文章:

javascript - jquery ui datepicker - 如何在一个日期选择器中设置两个最小/最大日期限制?

javascript - 使用 JavaScript 函数显示今天的约会/日期

javascript - Windows 10,资源解释为样式表但使用 MIME 类型应用程序/八位字节流传输

javascript - JavaScript 对象的表单输入

javascript - 异步/等待的竞争条件

javascript - 模态无法正常工作,CSS 未填充,<span> 损坏

javascript - Angular Material 1.1.1 布局填充问题与指令

javascript - Q.fcall总是失败

javascript - jQuery.data 会导致内存泄漏吗?

javascript - 遍历具有相同类的元素并删除它们