前端小知识集锦vtiger专题让前端飞

jquery.class.js的使用

2018-01-06  本文已影响14人  明月半倚深秋_f45e

最近在研究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中调用,也可以用PriceBooks_RelatedList_Js类名来调用(第一个大括号一般放通过 通过按钮 或者点击 这些由页面直接触发的方法)
2.第二个可以用对象.方法名 的方式调用 (放内部JS自身调用的方法)

<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

也可以通过 window['类名']的方式

var related2=new window["Price_RelatedList_Js"]();
    related2.sayHello();
上一篇 下一篇

猜你喜欢

热点阅读