Javascript :使用文字创建对象

Javascript : Creating Objects using Literals

本文关键字:文字 创建对象 Javascript      更新时间:2023-09-26

我一直在学习初学者js,并遇到过使用文字创建对象。代码如下:

斯菲德尔

<script>
    var phone= {
    name : "iPhone",
    brand : "Apple",
    version : "5",
    edition : function(){
        alert("The cellphone's Version  is iPhone" + this.version);
    };
    function demo(){
         console.log(phone.brand); 
         console.log(phone.version); 
         console.log(phone.name); 
    }
</script>
<p>Click the button below</p>
<button onclick="demo();">JS Object Literals</button>

但是,每当单击该按钮时,demo()函数都不会显示任何内容。

请任何人帮助我指出错误。

问题是语法错误。

您缺少最后的},函数之后不应出现;

var phone= {
    name : "iPhone",
    brand : "Apple",
    version : "5",
    edition : function(){
        alert("The cellphone's Version  is iPhone" + this.version);
    }
};

http://jsfiddle.net/gaby/cr8nbjvw/2/演示


在 jsfiddle 上直接从 DOM 元素属性调用函数时,您需要在下拉菜单(上/左)中选择 No wrap - in <head> 选项,以便您的方法是全局的。

你在 html 中的 js + 中混淆了大括号,你必须调用phone.demo()

在jsfiddle中,如果你想从html访问电话,不要把var放在前面(它使它私有到特定的js闭包,并且无法访问全局空间)

.html

<button onclick="phone.demo();">JS Object Literals</button>

.js

phone= {
    name : "iPhone",
    brand : "Apple",
    version : "5",
    edition : function(){
        alert("The cellphone's Version  is iPhone" + this.version);
    },
    demo: function(){
        console.log(phone.brand); 
        console.log(phone.version); 
        console.log(phone.name); 
    }
}