简体   繁体   中英

Is it possible to have JavaScript object evaluate to a primitive

I would like to be able to define an object that will evaluate to a primitive but also may have attached functions. Effectively the same way the "String" class works. Is there a way for me to extend the class without modifying the String prototype.

One use case for me would be like this:

class ID extends String{
   constructor(len){
      let value = 'Very unique id';
      this.len = len;
      this = value; //Or some other way of assigning the objects value
   }
   someRandomFunction(){
      console.log('I was called');
   }
}

const newId = new ID(10);
console.log(newId) // prints "Very unique id"
newId.someRandomFunction() // prints "I was called"
console.log(newId.len) // prints "10"

Most situations where this will be relevant, you will be implicitly calling newId[Symbol.toPrimitive]() . You can define this function on your object, which will result in being able to precisely define how your object behaves when you attempt to use it as different things.

In your case, it's a wrapper object around a string value, right? You could simply return the string for all calls to toPrimitive , and thus any attempt to use your object as anything other than an object will result in the operation being performed on the backing string instead. Here's an example:

 class ID { constructor(len){ this.value = 'Very unique id'; this.len = len; } [Symbol.toPrimitive](hint){ return this.value; } someRandomFunction(){ console.log('I was called'); } } const newId = new ID(10); console.log('' + newId) // prints "Very unique id" newId.someRandomFunction() // prints "I was called" console.log(newId.len) // prints "10"

Note that console.log is a bit of a finicky function: it checks the type of the argument (which you cannot change) and if it's an object, it won't coerce it to anything but run some code to inspect the object's properties. So console.log(newId) you'll never get to have a satisfying custom output (unless you're in node.js). It will always print like an object. However, any attempt to coerce the object to a primitive, as in '' + newId will result in your desired behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM