JavaScript中对象定义时语句以逗号或分号结尾的区别

3

大家好,我对JavaScript的面向对象编程不太熟悉,经过一些尝试后,我在对象定义方面有一些小困惑。请帮忙检查下面的代码和注释。谢谢。

    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 .

        };

1
我认为这个问题需要移动到“代码审查”或“程序员”板块。 - Red
嗨,@Red,代码审查和程序员在哪里?你能给我一个链接吗?下次我会关注的。谢谢。 - Joe.wang
请访问以下网站:http://programmers.stackexchange.com/?as=1,http://codereview.stackexchange.com/?as=1。同时,不要错过其他优秀的Stack交流社区。 - Red
3个回答

4

如果你正在压缩代码,最好使用分号(;),这样代码可能会变成其他形式,例如:var foo = 1; var bar = 2; 此外,在压缩时避免使用//进行注释,因为它会注释掉该行的其余部分。 - Hiny

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";
            }
};

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


0

this.GetOriginalSource=function(){ 将该函数添加到对象中。在此行之前,它不存在。但是你试图在它之前调用它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接