我想创建一个具有许多属性的对象,但是当我只用console.log记录我的对象或将其插入到评估中时,它确实具有一个默认值来评估或记录,例如:例。
我尝试使用getter和setter,但没有成功。
const obj = { a: 'test1', b: 'test2' } // this is my object
console.log(obj.a); // this should return 'test1'
console.log(obj); // this should return a value of my choice, like 'testobj' or a number
'testobj' === obj; // should be true, since I want my obj to have a default value of 'testobj' in evaluations
// just like a primitive type, like strings or numbers. They have many functions and a default value
[将对象视为字符串时,JavaScript运行时将查看其是否具有toString()
方法,并将返回该方法指示的内容。如果没有toString()
,则通常会看到[object Object]
。
此外,在制作将以这种方式使用的对象时,请使用构造函数,而不要使用对象文字。
const objA = function(){ this.a= 'test1'; this.b= 'test2' }
let instA = new objA();
console.log(instA.toString());
const objB = function() { this.a= 'test1'; this.b= 'test2'; this.toString= function(){ return this.a; }}
let instB = new objB();
console.log(instB.toString());