0

Here is a simplified example of the problem I am having.

function Part(price, qty) {
  this.price = price;
  this.qty = qty;
  this.value = function() {
    return this.price * this.qty
  }
}

var fancyPart = new Part(2, 3);


console.log(fancyPart.value)

I would like for this to print 6 to the console, instead it is printing:

function () {
    return this.price * this.qty
  }

Why is this happening?

I am trying to use this to create an "object" and was reading about the various methods over at this question: Which way is best for creating an object in javascript? is "var" necessary before variable of object?

3
  • 4
    console.log(fancyPart.value()) — you have to call the function. Commented Jan 19, 2018 at 1:03
  • @Pointy... Thanks. That was so obvious. Commented Jan 19, 2018 at 1:05
  • 1
    Or you could implement value as a getter. ;-) Commented Jan 19, 2018 at 1:17

4 Answers 4

1

You could use the class syntax and add value as a getter:

class Part {
  constructor (price, qty) {
    this.price = price;
    this.qty = qty;
  };

  // Implement value as a getter
  get value() {
    return this.price * this.qty
  };

}

var fancyPart = new Part(2, 3);

// No need for parameter list
console.log(fancyPart.value)

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

1 Comment

Thanks. This is what I was trying to do - just using the incorrect terminology.
0

try console.log(fancyPart.value())... to invoke(call) the function

function Part(price, qty) {
  this.price = price;
  this.qty = qty;
  this.value = function() {
    return this.price * this.qty
  }
}

var fancyPart = new Part(2, 3);


console.log(fancyPart.value())

Comments

0

You can from your constructor that value is being assigned as a function

this.value = function() { return this.price * this.qty }

Hence when you try to log fancyPart.value, you are actually logging the function and not it’s invocation.

If you as “()” after value, you will actually invoke the function and get the evaluation you expect (I.e 6 in case of fancypants.value)

Comments

0

Or you can be different and use Function.prototype.call

function Part(price, qty) {
  this.price = price;
  this.qty = qty;
  this.value = function() {
    return this.price * this.qty
  }
}

var fancyPart = new Part(2, 3);


console.log(fancyPart.value.call(fancyPart))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.