0

I am a typical Java programmer with traditional OOPs knowledge. I am trying to learn JS now. I have learned that a function is JS is a first class object, like any other object it has properties and methods. based on this I have written following code:

function Note(name, text)
{
    this.name = name;
    this.text = text;

   function displayNote()
    {
       alert(this.text);
    }
}

I am now trying to access the displayNote function from the not object, with the follwing code:

var note = new Note("a", "c");
alert(note.displayNote);

But it alerts undefined. This may be due to the scope issue. So I tried with this:

function Note(name, text)
{
    this.name = name;
    this.text = text;

   function displayNote()
    {
       var self = this;
       alert(self.text);
    }
}

var note = new Note("a", "c");
alert(note.displayNote);

Still the same result. Any explanations?

1

4 Answers 4

2

You need to do:

function Note(name, text)
{
    this.name = name;
    this.text = text;

    this.displayNote = function()
    {
       alert(this.text);
    }
}

It is showing undefined, because you haven't defined the displayNote property.

Also, to call a function you need to do:

var note = new Note("a", "c");
note.displayNote();// it will automatically alert. Otherwise you'll have two alerts. The second one being undefined.

Live Demo

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

Comments

1

Try this.

this.displayNote = function()
{
   alert(this.text);
}

Now it's a property of the Note object. Plus I think you want to do this:

note.displayNote(); // Note the brackets to call.

Comments

0

In here with the code as

alert(note.displayNote);

You are calling the alert twice.

So please just call the function

note.displayNote();

Comments

0

you can use like below

<script language="javascript" type="text/javascript">
<!--

person = new Object()
person.name = "Tim Scarfe"
person.height = "6Ft"

person.run = function() {
    this.state = "running"
    this.speed = "4ms^-1"
}

//-->
</script>

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.