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?

blackandorangecat
  • 1,246
  • 5
  • 18
  • 37

4 Answers4

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)
RobG
  • 142,382
  • 31
  • 172
  • 209
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())
Firas Omrane
  • 894
  • 1
  • 14
  • 21
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)

KnightFox
  • 3,132
  • 4
  • 20
  • 35
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))
tay_rex
  • 46
  • 4