简体   繁体   English

从对象访问属性/方法(javascript)

[英]Accessing properties/ methods from objects (javascript)

I am a typical Java programmer with traditional OOPs knowledge. 我是具有传统OOP知识的典型Java程序员。 I am trying to learn JS now. 我正在尝试学习JS。 I have learned that a function is JS is a first class object, like any other object it has properties and methods. 我了解到,函数JS是一流的对象,就像它具有属性和方法的任何其他对象一样。 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: 我现在尝试使用以下代码从not对象访问displayNote函数:

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. 它显示为undefined,因为您尚未定义displayNote属性。

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. 现在,它是Note对象的属性。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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