例如,如何创建像字符串这样的对象?具有许多属性和默认控制台的对象。log/evaluation 值

How can I create a object like a string, for example? A object with many properties, and a default console.log/evaluation value

我想创建一个具有许多属性的对象,但是,当我 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() 方法,并会 return 该方法指示的任何内容。如果没有 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

一年后我运行再次进入这个问题并找到了解决方案。我的 objective 是用一些方法创建一个 string/number ,这些方法会使用它自己 (this) 来生成输出值,并且可以在您的代码中用作普通的 number/string 而无需转换或任何东西就像那样,就像一个普通的 JS number/string.

有点像一个数字,它有自己的值,但你可以访问 number.negative 属性,你将得到与你的数字相等的负值。您可以创建一个 class 来扩展您要使用的原始类型,例如,对于数字,我可以使用:

class Num extends Number {
  negative = this * (-1);
  // I can even add a few methods that receive props to calculate new output values
  exponential(exp) {
    let result = 1;
    while(exp-- > 0) {
      result *= this;
    }
    return result;
  }
}

const myNum = new Num(3);

console.log('Simple sum: ', 1 + myNum); // outputs 4

console.log('Negative: ', myNum.negative); // outputs -3

console.log('Exponential: ', myNum.exponential(2)); // outputs 9

上面的代码也适用于字符串。希望我能帮助别人。