0

As new on JS developpment, I've started the OOP which from my point of view is the more dificult but also the most intersting part of JS.

There is my code :

var calc = function(num1, num2){
  this.num1 = num1;
  this.num2 = num2;
  this.addNum2 = function(number){
    this.num2 = number;
  }
}

And now, I'm trying to use the function addNum2to set the num2 with

calc.addNum2(24)

I got this return:

VM495:1 Uncaught TypeError: calc.addNum2 is not a function

I'm just here to understand how it works so any help would be precious. Thank you all!

1
  • 2
    calc is a construtor which constructs an object which has the method addNum2. You use it as new calc(a, b) first… Commented Nov 3, 2019 at 10:40

1 Answer 1

3

You need to invoke function with new operator

function calc(num1, num2) {
  this.num1 = num1;
  this.num2 = num2;
  this.addNum2 = function(number) {
    this.num2 = number;
  }
}

let newCalc = new calc()
newCalc.addNum2(2)
console.log(newCalc.num2)


Or you need to return this from function

function calc(num1, num2) {
  this.num1 = num1;
  this.num2 = num2;
  this.addNum2 = function(number) {
    this.num2 = number;
  }
  return this
}

let newCalc = calc()
newCalc.addNum2(2)
console.log(newCalc.num2)


i would like to do let's say : newCalc.addNum2(4).mutiply(5);

function calc(num1, num2) {
  this.num1 = num1;
  this.num2 = num2;
  this.addNum2 = function(number) {
    this.num2 = number;
    return this
  }
  this.multiply = function(number){
    this.num2 = this.num2 * number
    return this
  }
  return this
}

let newCalc = calc()
newCalc.addNum2(2).multiply(3)
console.log(newCalc.num2)

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

5 Comments

You're missing the arguments to calc
@deceze i left intentionally so i can show the function is actually changing the value. but yes i could have used different values too
Thank you so much for your answer! My main concern was, is it possible to call "calc" without giving him parameter, and set it later with "addNum" and I can see it's possible! Thanks so much!
@CodeManiac Just last question, if for example i would like to do let's say : newCalc.addNum2(4).mutiply(5); In that case, how shall i structure it?
@Kevkeev13 You need to return this from functions so you can chain methods. so you need to return this from both addNum2 and multiply function. see the last snippet you can do something like this

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.