繁体   English   中英

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

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

我是具有传统OOP知识的典型Java程序员。 我正在尝试学习JS。 我了解到,函数JS是一流的对象,就像它具有属性和方法的任何其他对象一样。 基于此,我编写了以下代码:

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

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

我现在尝试使用以下代码从not对象访问displayNote函数:

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

但是它会发出未定义的警报。 这可能是由于范围问题。 所以我尝试了这个:

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);

结果还是一样。 有什么解释吗?

您需要做:

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

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

它显示为undefined,因为您尚未定义displayNote属性。

另外,要调用一个函数,您需要执行以下操作:

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

现场演示

尝试这个。

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

现在,它是Note对象的属性。 另外,我认为您想这样做:

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

在这里的代码为

alert(note.displayNote);

您两次拨打警报。

所以请只调用函数

note.displayNote();

你可以像下面这样使用

<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