2

So I have this:

var setting = function (val,desc) {
    this.val = val;
    this.desc = desc;
};

var option = new setting(15,"This is a setting");

and I was wondering if I could get option to return value rather than the object.

I tried adding this to setting

var setting = function (val,desc) {
    this.val = vall;
    this.desc = desc;
    return this.val;
};

But it didn't work. Is it even possible? I'd like the option to return val, but still have option.val return val and option.desc to return desc.

2
  • this.val = val ? val : null is the same as this.val = val || null which can be just this.val = val in your context, since null == undefined Commented Dec 24, 2013 at 8:18
  • ...good point, editing. Commented Dec 24, 2013 at 8:20

3 Answers 3

2

You can assign the toString method manually to overwrite what happens when the object is treated like a string.

Do note that although it will allow you to treat the object like a string, you cant rely on it acting like one in all situations, especially in situations where you can normally use string functions. (things like .split etc. will not work unless you define them manually)

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

4 Comments

I tried adding this.prototype.toString = function(){ return this.val } but it didn't work.
@DaltonGore just this.toString no need for the prototype
I just tried it here, and it doesn't appear to be working:jsfiddle
@DaltonGore console.log is one of those exceptions I mentioned, try alert instead and it will work
2
var option = (new setting(15,"This is a setting")).val;

is that enough?

1 Comment

Wouldn't that just assing option to 15, though?
1

If a constructor function returns nothing, null, or any atomic / non-object value then said value is ignored and the newly created object reference is given back to the caller. so...

var setting = function (val,desc) {
    this.val = val ? val : null;
    this.desc = desc ? desc : null;
    return {val : this.val}
};

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.