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

对象定义时以逗号或分号结尾的Javascript语句,javascript,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 f

总之,我不熟悉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 .

        };

this.GetOriginalSource=function(){
将函数添加到对象中。它不在此行之前。但您尝试在之前调用它。

尝试以下操作:

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";
            }
};
您正在尝试调用尚未在运行时定义的函数

  • 在调用函数之前,必须先定义它
  • javascript中的分号是可选的。基本上,分号用于结束语句,而逗号用于处理对象。您可以尝试阅读这些文章并
  • Javascript可以用面向对象的方式编写。请看,但我建议您使用它,它会让您的生活更轻松


    你可能需要这个,但读起来并不是那么有趣:)

    我认为这个问题需要转移到
    codeReview
    程序员那里去。嗨,@Red,codeReview和程序员在哪里。你能给我一个链接吗。下次我会关注它。谢谢。还可以查看一下令人惊叹的堆栈网站。如果你正在压缩在您的代码中,最好使用分号(;),因此代码可能会变成其他代码,例如:var foo=1var bar=2;此外,在压缩时,避免使用//进行注释,因为它将注释行的其余部分