javascript - 有没有一种简单的方法可以将对象名称转换为字符串,然后将该字符串添加到对象中名为 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())
解决方案
这应该有效:
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());
推荐阅读
- javascript - EDGE 在显示键盘输入时滞后
- azure-devops - 用于自动化而不是个人访问令牌的用户
- python - 在 matplotlib 图中配置网格线
- c# - 如何实现接口返回带有空方法体的 IAsyncResult
- python - 为什么即使请求详细信息相同,MS 图形浏览器和我的 python 请求结果也会不同
- sabre - SABRE:创建 PNR API 错误:ERR.SP.PROVIDER_ERROR
- nginx - 防止谷歌索引“deny_all”=错误403
- javascript - Gridview文本框焦点在垂直
- reactjs - react-intl 和 babel 不会导出消息,预设错误
- iis - 如何将 Angular 7 通用应用程序部署到 IIS