7

I'm looking to create a class so that it will return a value instead of the class object in ES6.

It's pretty much the same question as this but in ES6. This touches on it a little bit, but you still have to explicitly call a 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 currently it returns {value: 4}.

4
  • 3
    Why would you want to do something like this? That doesn't seem to make sense. What problem are you actually trying to solve? Commented Jun 22, 2015 at 0:09
  • foo is an object, not a primitive type, if you need to get just a value use a regular var value Commented Jun 22, 2015 at 0:11
  • 1
    If you don't want to create something that looks like a class, just use a function that returns a value. Why create a class if you don't want a class! Commented Jun 22, 2015 at 0:11
  • I'm creating a currency class. So it needs to retain a float value and return a string value. For example, 4.5689 and "$4.57". I've already created a library to do this in with helper functions. I just wanted to take ES6 classes for a test drive. :) Commented Jun 25, 2015 at 5:15

1 Answer 1

10

valueOf may help you with whatever it is 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 have to make sure you understand how valueOf works. According to the docs:

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

So simply referring to the object will not invoke valueOf, of course; that would leave you with no way to reference the underlying object. It is used in situations where it is necessary to coerce the object into a primitive, such as in +foo.

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.