简体   繁体   中英

Accessing properties/ methods from objects (javascript)

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?

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

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.

In here with the code as

alert(note.displayNote);

You are calling the alert twice.

So please just call the function

note.displayNote();

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM