对象定义时,以逗号或分号结尾的Javascript语句

时间:2013-03-12 10:09:16

标签: javascript

所有,我不熟悉javascript OO,在我做了一些实验后,我对对象定义有一些疑惑,请帮助我查看下面的代码和评论。谢谢。

    GlobalUtility = function() {
            this.templeteCode = "123";

            this.Init();
//why can not put this code here,
//there is an error says GetOriginalSource is not a function . 
//This is not like the classical OO constructor which can call any methods in class.
            this.Init = function() {
                var source=this.GetOriginalSource();
                alert(source + " is ok.");
            },//I found I can end this statement by , or ; Is there any difference between them?

            this.GetOriginalSource=function(){
                return "abc";
            };
            //this.Init(); putting this code here is ok .

        };

3 个答案:

答案 0 :(得分:3)

  1. 您必须在调用之前定义一个函数。
  2. javascript中的分号是可选的。基本上,分号用于结束语句,而逗号是在处理对象时。您可以尝试阅读这些文章JavaScript variable definition: Commas vs. SemicolonsDo you recommend using semicolons after every statement in JavaScript?
  3. Javascript可以用oop方式编写*请参阅defining javascript class但我建议使用Base.js,这会让您的生活更轻松。

    你可能需要这个,但阅读:) javascript patterns

    并不是那么有趣

答案 1 :(得分:1)

试试这个:

GlobalUtility = function () {
            Init();


            this.templeteCode = "123";
            this.Init = Init;       
            this.GetOriginalSource = GetOriginalSource;

            //function declaration
            function Init() {
                var source = GetOriginalSource();
                alert(source + " is ok.");
            }
            function GetOriginalSource() {
                return "abc";
            }
};

您正在尝试调用尚未在运行时定义的函数。

答案 2 :(得分:0)

this.GetOriginalSource=function(){将该函数添加到对象中。它不在此之前。但你以前试着打电话。