原生 JavaScript 插件开发学习
插件一般把它放到一个闭包用来与外部变量隔绝以防污染全局变量.
- !(function(){
- })()
插件制作步骤:
(一) 构造函数 使用时 new 一下生成新的实例
- var myUtil=function(name,age){
- this.name=name;
- this.age=age;
- }
(二) 使用原型模式 可以让多个实例的使用一个方法
- var myUtil=function(name,age){
- this.name=name;
- this.age=age;
- }
- myUtil.prototype={
- // 将构造函数置为 MathUtil, 这里一定要将 constructor 重新设置回 MathUtil, 不然会指向 Object 的构造函数
- constructor:myUtil,
- add: function(a, b) {
- var result= a + b;
- alert("result ==" + result);
- }
- }
(三) 创建一个闭包用来与外部变量隔绝以防污染全局变量. 把以上代码放入其中
- (function(Windows){
- var myUtil=function(name,age){
- this.name=name;
- this.age=age;
- }
- myUtil.prototype={
- // 将构造函数置为 MathUtil, 这里一定要将 constructor 重新设置回 MathUtil, 不 然会指向 Object 的构造函数
- constructor: MathUtil,
- add: function(a, b) {
- var result= a + b;
- alert("result ==" + result);
- }
- }
- Windows.myUtil=myUtil;// 把代码挂载到 Windows 上以便外面调用
- })(Windows)
(四) 使用时 new 一下就可以调用里面的方法了
- !(function(Windows) {
- var myUtil = function(name, age) {
- this.name = name;
- this.age = age;
- }
- myUtil.prototype = {
- // 将构造函数置为 myUtil, 这里一定要将 constructor 重新设置回 myUtil, 不 然会指向 Object 的构造函数
- // 有轻度强迫症的表示最好重定向回来, 避免挖坑
- constructor: myUtil,
- add: function(a, b) {
- var result = a + b;
- alert("result ==" + result);
- }
- }
- Windows.myUtil = myUtil; // 把代码挂载到 Windows 上以便外面调用
- })(Windows)
- var v1 = new myUtil("hellow", 14);
- v1.add(3,5);
这样一个 JavaScript 插件小 demo 就完成了
来源: http://www.bubuko.com/infodetail-2805261.html