javascript - 例如,如何创建一个像字符串这样的对象?具有许多属性和默认 console.log/evaluation 值的对象

标签 javascript object types getter primitive

我想创建一个具有许多属性的对象,但是,当我只是 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/

相关文章:

javascript - extjs 基于另一个组合框值过滤组合框

javascript - cloneNode 并对所有节点(父节点+子节点)的值求和。 JavaScript

javascript - 如何在数据数组和对象的合并中使用对象分配而不是扩展语法?

Python Int 对象不可调用

javascript - 无法从维基百科 API 获取数据

javascript - 使用 ReactJs 从父元素到子元素获取点击 ID

java - 通过字符串获取实例化对象

c# - C# 中的泛型,使用变量类型作为参数

c# - 为什么 null 不是 Nullable<> 类型的实例?

c# - 为什么 IsAssignableFrom 在将可空值与接口(interface)进行比较时返回 false?