将对象作为参数传递时如何获取其名称?使用模板字面量未成功
问题解决方案
根本原因
直接把普通对象放入模板字面量时,JS会自动调用对象的默认toString()方法,原生JS普通对象的该方法返回值固定为[object Object],因此无法得到预期输出。
不同场景实现方案
场景1:需要输出对象的实际内容
这是最常见的需求,有两种常用实现方式:
- 用
JSON.stringify()序列化对象后输出:
const theObject = { prop1: "sth", prop2: "sthesee" } function theFun(theArg) { // 如需格式化缩进可以加后两个参数:JSON.stringify(theArg, null, 2) console.log(`${JSON.stringify(theArg)}`); } theFun(theObject);
- 给对象自定义
toString()方法,适配模板字面量的自动转换逻辑:
const theObject = { prop1: "sth", prop2: "sthesee", toString() { // 自定义输出格式即可 return `{ prop1: ${this.prop1}, prop2: ${this.prop2} }`; } } function theFun(theArg) { console.log(`${theArg}`); // 自动调用自定义toString方法输出预期内容 } theFun(theObject);
场景2:需要获取对象对应的变量名字符串theObject
JS运行时默认不会存储值对应的变量名,因此需要手动绑定标识,两种实现方案:
- 给对象添加
name属性存储标识:
const theObject = { name: "theObject", prop1: "sth", prop2: "sthesee" } function theFun(theArg) { console.log(`${theArg.name}`); // 输出 theObject } theFun(theObject);
- 传参时用对象解构包装,直接提取键名:
const theObject = { prop1: "sth", prop2: "sthesee" } function theFun(wrappedArg) { const objName = Object.keys(wrappedArg)[0]; console.log(objName); // 输出 theObject const originalObj = wrappedArg[objName]; // 可同时拿到原对象内容 } // 传参时用{ 变量名 }的结构包装 theFun({ theObject });
内容的提问来源于stack exchange,提问作者Wheelwright
相关产品推荐
相关产品推荐

