1、方式一
创建App.js
var App = App || {};
var global = window;
App.ns = function (nsStr) {
var parts = nsStr.split("."),
root = global,
max,
i;
for (i = 0, max = parts.length; i < max; i++) {
//如果不存在,就创建一个属性
if (typeof root[parts[i]] === "undefined") {
root[parts[i]] = {};
}
root = root[parts[i]];
}
return root;
};
//通用的方法
App.utils = {
validation: {
isUndefined: function (obj) {
return undefined === obj;
},
isNumber: function (value) {
return typeof (value) == "number" ? true : false;
},
}
}
App.validation = App.utils.validation;
创建index.js
App.ns("TS.textCount");
TS.textCount = {
input: null,
init: function (config) {
let a = App.validation.isNumber(2); //调用app中函数
console.log(a);
this.input = $(config.id);
this.render(false);
this.bind();
return this;
},
bind: function () {
var self = this;
this.input.on('keyup', function () {
self.render(true);
})
},
getNum: function () {
return this.input.val().length;
},
render: function (flag) {
var num = this.getNum();
if (num == 0 && !flag) {
this.input.after('<span id="j_input_count"></span>')
}
$('#j_input_count').html(num + '个字');
}
}
在html中使用
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="App.js"></script>
<script src="index.js"></script>
<script>
$(function () {
TS.textCount.init({ id: '#j_input' });
})
</script>
<body>
<input type="text" id="j_input">
</body>
2、方式二(namespace方式)
创建App.js
$.namespace = function () {
var a = arguments, o = null, i, j, d;
for (i = 0; i < a.length; i = i + 1) {
d = a[i].split(".");
o = window;
for (j = 0; j < d.length; j = j + 1) {
o[d[j]] = o[d[j]] || {};
o = o[d[j]];
}
}
return o;
};
$.namespace('App.utils')
App.utils = {
isUndefined: function (obj) {
return undefined === obj;
},
//是否数字
isNumber: function (value) {
return typeof (value) == "number" ? true : false;
},
}
创建index.js
$.namespace('Mo.frame');
Mo.frame = {
age: '12',
init: function () {
let name = Mo.menu.name;
return name;
}
}
在html中使用
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="App.js"></script>
<script src="index.js"></script>
<script>
let isNumber = App.utils.isNumber('1');
console.log(isNumber);
console.log(Mo.frame.init())
</script>