1

I am extremely new to JavaScript so please bear with me on this one. Here is a snippet of my code:

function Course(title, instructor, views){

  this.title= title;
  this.instructor = instructor;
  this.views = views;
  this.updateViews = function() {
    return ++this.views;
  };

}

var course1 =   new Course('JS', 'Sarun', 0);

console.log(course1.updateViews);

On execution however, I had expected the value of course1.updateViews to be 1. Instead, I get the entire function displayed in the console as follows:

ƒ () {
    return ++this.views;
  }

I am sure that this is a beginner's mistake. So can anyone please Correct me on this?

2 Answers 2

4

So can anyone please Correct me on this?

You need to invoke the function using ()

console.log(course1.updateViews());

function Course(title, instructor, views){

  this.title= title;
  this.instructor = instructor;
  this.views = views;
  this.updateViews = function() {
    return ++this.views;
  };

}

var course1 =   new Course('JS', 'Sarun', 0);

console.log(course1.updateViews());

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

1 Comment

yup this helps!! thanks a lot!! Silly mistake from my side
0

Because in the Course object, you declared this.updateViews as function. if you wanna get return value of function, you need to invoke that by calling:

console.log(course1.updateViews());

if you wanna updateViews is static attribute you can change the way to declare this:

function Course(title, instructor, views){

  this.title= title;
  this.instructor = instructor;
  this.views = views;
  this.updateViews = ++this.views;

}

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.