Javascript对象属性不在范围内 [英] Javascript object property not in scope

查看:116
本文介绍了Javascript对象属性不在范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎对对象的属性范围有疑问.我想将每个Message对象的titlemessage属性输出到select元素,但这是不起作用!我做错了什么

I seem to have a problem with objects' properties' scope. I would like to output each of the Message objects' title and message properties to a select element, but it is Not Working! What am I doing incorrectly

<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
    function Message(title, message) {
        this.title=title;
        this.message=message;
        this.getTitle = function(){
            return this.title;
        };
        this.getMessage = function(){
            return this.message;
        };
    }
    var messages = new Array(
        new Message("First Title", "This is the first message"),
        new Message("Second Title", "This is another message")
    );
    function updateSelect () {
        $("#cannedMessages_button").empty();
        for (c in messages) {
            // First try, with getters and setters
            $("#cannedMessages_button").append($('<option>', { value : c.getMessage() , text : c.getTitle() }));
            // Second try, directly
            $("#cannedMessages_button").append($('<option>', { value : c.message , text : c.title }));
        }
    }
    updateSelect();
});
</script>
</head><body>
<form><select id="cannedMessages_button"></select></form>
</body></html>

我可以验证foreach实际上正在运行两次迭代,但是我无法从对象中获取值.

I can verify that the foreach is in fact running two iterations, but I cannot get the values out of the objects.

推荐答案

不要使用for (c in messages).

in用于迭代对象的属性,而不用于迭代数组中的值.

in is for iterating over properties of an object, not for iterating over values in an array.

使用久经考验的

for(var i = 0; i < messages.length; i++) {
...
}

此外,您不会将getTitlegetMessage方法放在原型上,这是一种浪费.

Also, you are not putting your getTitle and getMessage methods on a prototype, which is kind of wasteful.

这篇关于Javascript对象属性不在范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆