首页 > 解决方案 > 有没有一种简单的方法可以将对象名称转换为字符串,然后将该字符串添加到对象中名为 objName 的属性中?

问题描述

我希望以下代码返回“小猎犬的名字是史努比 daSilva”。

我想我需要的是能够访问对象名称并将其转换为字符串,也许将其保存为属性,然后将其添加到 fullNameDescription (它目前说???这个对象名称???)

更好的是,我可以将对象名称作为字符串保存到实际对象中的属性中,例如 this.objName = ???

function Dog(firstName, secondName) {
  this.firstName = firstName;
  this.secondName = secondName;
  this.fullNameDescription = function(){return("The " + ???this object name??? + "'s name is " + this.firstName + " " + this.secondName)}
}


let beagle = new Dog("Snoopy", "daSilva");


console.log(beagle.fullNameDescription())

标签: javascriptobject

解决方案


这应该有效:

function Dog(firstName, secondName, type) {
  this.firstName = firstName;
  this.secondName = secondName;
  this.type = type;
  this.fullNameDescription = function(){
    return `The ${type}'s name is ${firstName} ${secondName}`;
  }
}

let beagle = new Dog("Snoopy", "daSilva", “beagle”);

console.log(beagle.fullNameDescription());

推荐阅读