所有,我不熟悉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 .
};
答案 0 :(得分: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(){
将该函数添加到对象中。它不在此之前。但你以前试着打电话。