我对Javascript和Web开发完全陌生。当我编写网页时,我创建了两个Javascript代码
<script src="./js/jquery.js"></script>
<script src="./js/ABuilder.js"></script>
<script src="./js/BBuilder.js"></script>
<script>
$(document).ready()
{
initA();//a function from A
}
</script>
当我打开网页时,我检查了调试器,函数initA没有执行。当我删除。
<script src="./js/BBuilder.js"></script>
initA按我的预期运行。但是,由于我还没有初步确定Bbuilder,Bbuilder怎么能影响到Abuger呢?
关于Bbuilder的详细代码
var day;
var month;
function initB() {
var dataFile = "./js/b.json";
loadData(dataFile, loadB);
}
function loadData(jsonFile, callback) {
$.getJSON(jsonFile, function(json) {
callback(json);
});
}
function loadB(data) {
day = data.day;
month = data.month;
}
Abuild Code
var age;
var gender;
function initA() {
var dataFile = "./js/a.json";
loadData(dataFile);
}
function loadData(jsonFile) {
$.getJSON(jsonFile, function (json) {
loadA();
});
}
function loadA(data) {
age = data.age;
gender = data.gender;
}`
答案 0 :(得分:0)
要包装ABuilder
和BBuilder
并防止变量冲突,您可以将它们分为两类。这样,可以定义这两个js文件之间的多态关系。
请检查以下代码段。在此示例中,定义了类ABuilder
和类BBuilder
。然后,BBuilder
定义为从ABuilder
延伸,但覆盖loadData()
方法。
// ./js/jquery.js
// ./js/ABuilder.js
function ABuilder() {
this.age = null;
this.gender = null;
}
ABuilder.prototype = {
initA: function() {
var dataFile = "./js/a.json";
this.loadData(dataFile);
},
loadData: function(jsonFile) {
$.getJSON(jsonFile, function(json){
this.loadA();
}.bind(this));
},
loadA: function(data) {
this.age = data.age;
this.gender = data.gender;
}
};
// ./js/BBuilder.js
function BBuilder() {
this.day = null;
this.month = null;
}
let aBuilderObj = new ABuilder();
aBuilderObj.initB = function() {
var dataFile = "./js/b.json";
this.loadData(dataFile, this.loadB);
};
aBuilderObj.loadData = function(jsonFile, callback) {
$.getJSON(jsonFile, function(json) {
callback(json);
});
};
aBuilderObj.loadB = function(data) {
this.day = data.day;
this.month = data.month;
};
BBuilder.prototype = aBuilderObj;
// init script
$(document).ready(function() {
let initedABuilder = new ABuilder();
initedABuilder.initA();
});
&#13;