ant*_*et2 6 javascript oop javascript-objects
我正在构建一个基于javascript的应用程序,它在移动和桌面设备上的工作方式不同.但是,除了DOM操作之外,大多数代码在两个平台之间都是通用的,所以我构建了所有文件,如:*foo.core.js*foo.mobile.js*foo.web.js
并希望利用面向对象技术编写更清晰的代码.
我有两个JavaScript文件,带有类
档案1:
function ClassA()
{}
ClassA.prototype.foo = function(){};
GreatGrandChildA.prototype = new GrandChildA(); // this is where the error is
function GreatGrandChildA ()
{}
Run Code Online (Sandbox Code Playgroud)
文件2:
ChildA.prototype = new ClassA();
function ChildA () // ChildA inherits ClassA
{}
GrandChildA.prototype = new ChildA()
function GrandChildA () // GrandChildA inherits ClassA
{}
Run Code Online (Sandbox Code Playgroud)
通常,在像C++这样的语言中,我会GrandChildA在文件1中转发声明.我想知道如何在Javascript中执行它
如果我创建一个包含所有四个类的单个文件 - 按照加载它们的顺序,该示例完全按预期工作:
无序js文件加载的简单逻辑:
文件1:
// ClassB: inherite from ClassA
(function ClassB_Builder() {
if(window.ClassB)return; // ClassB is already defined;
if(!window.ClassA) { // ClassA is already not defined;
setTimeout(ClassB_Builder,0); // shedule class building
return;
}
ClassB=function() {
}
ClassB.prototype=new ClassA;
ClassB.prototype.constructor=ClassB; // can be important for inheritance!!!
})();
Run Code Online (Sandbox Code Playgroud)
文件2:
// ClassA: base class
(function ClassA_Builder() {
ClassA=function() {
}
})();
// ClassC: inherite from ClassB
(function ClassC_Builder() {
if(window.ClassC)return; // ClassC is already defined;
if(!window.ClassB) { // ClassB is already not defined;
setTimeout(ClassC_Builder,0); // shedule class building
return;
}
ClassC=function() {
}
ClassC.prototype=new ClassB;
ClassC.prototype.constructor=ClassC; // can be important for inheritance!!!
})();
Run Code Online (Sandbox Code Playgroud)