Returns JavaScript class value instead of object reference (in ES6)

I want to create a class so that it returns a value instead of a class object in ES6.

This is almost the same question as this but in ES6. This touches it a bit, but you must still explicitly reference the property.

I want to do something like:

class Foo {
  constructor(value) {
    this.value = value;  // returns an object other than *this*.
  }
}    

var foo = new Foo(4);
console.log(foo) // 4

      

But he is currently returning {value: 4}

.

+3


source to share


1 answer


valueOf

can help you with what you are trying to do:

class Foo {
  constructor(value) {        this.value = value; }
  valueOf()          { return this.value;         }
  ^^^^^^^^^
}    

var foo = new Foo(4);
console.log(+foo) // 4

      

You need to make sure you understand how it works valueOf

. According to the docs :



JavaScript calls the valueOf method to convert an object to a primitive value.

So just referring to the object won't call valueOf

, of course; which won't give you a reference to the underlying object. It is used in situations where it is necessary to force an object to a primitive, for example, in +foo

.

valueOf

has nothing to do with ES6; it is available for all objects.

+6


source







All Articles