我想创建一个具有许多属性的对象,但是,当我只是 console.log 我的对象或将其插入到评估中时,它确实有一个要评估或记录的默认值,一个原始值,例如“test”,例如。
我尝试使用 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]
。此外,要生成底层原始值,请为对象指定一个 valueOf
值。
此外,在创建将以这种方式使用的对象时,请使用构造函数,而不是对象文字。
const objA = function(){ this.a= 'test1'; this.b= 'test2' }
let instA = new objA();
console.log(instA.toString());
const objB = function() {
this.a= 5;
this.b= 'test2';
this.toString= function(){ return this.a; };
this.valueOf = function() { return this.toString(); };
}
let instB = new objB();
console.log(instB.toString());
console.log(instB + 2); // Get the primitive and work with that
关于javascript - 例如,如何创建一个像字符串这样的对象?具有许多属性和默认 console.log/evaluation 值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58564886/