最近在研究 vtiger 的 JS 的使用
它的 JS 在我看来是一个非常不错的写法, 用的是面向对象的思维
首先来说一下这个 jquery.class.js
这个库能够非常容易的创建 js 类 和 继承
在页面多的时候非常推荐使用, 而且现在前端模块化非常常见
下面来说他的用法 (网上完全找不到文档, 全凭自己摸索)
vtiger 的用法是, 每一个模块下都有几个 js 文件, 每一个 JS 文件就是一个对象
现在我来声明一个类, PriceBooks_RelatedList_Js
jQuery.Class("PriceBooks_RelatedList_Js",{gettest:function(){
console.log(123);
}
},{
showtest:function(){
console.log(123);
},
auto:function(){
PriceBooks_RelatedList_Js.gettest();
},
registerEvents:function(){
this.showtest();
}
});
在加载两个文件之后, 上面的类就建好了
<script src="jquery-1.11.3.js"></script>
<script src="jquery.class.min.js"></script>
对象的名称是 PriceBooks_RelatedList_Js
大家发现里面有两个大括号, 里面都能写方法
区别 1. 第一个大括号里面的方法, 不能用 this 调用, 可以在标签的 onclick 中调用
2. 第二个可以用对象. 方法名 的方式调用
<body>
<button onclick="PriceBooks_RelatedList_Js.gettest()"> 调用 </button>
<script src="jquery-1.11.3.js"></script>
<script src="jquery.class.min.js"></script>
<script>
jQuery.Class("PriceBooks_RelatedList_Js",{
gettest:function(){
console.log(1234);
}
},{
showtest:function(){
console.log(123);
},
registerEvents:function(){
this.showtest();
}
});
jQuery(document).ready(function (e) {
var instance = new PriceBooks_RelatedList_Js();
instance.registerEvents();
});
接着我们来讲第二点, 继承
PriceBooks_RelatedList_Js 是我们要继承的类
Price_RelatedList_Js 是我们的子类
子类能够调用父类的方法
PriceBooks_RelatedList_Js("Price_RelatedList_Js",{},{
sayHello:function(){
console.log("hello");
}
});
var related=new Price_RelatedList_Js();
related.sayHello();// 输出自己的方法 hello
related.showtest();// 输出父类的方法 123
来源: http://www.jianshu.com/p/2c00992b77aa