用js面向對象思想封裝插件


js是基於原型的面向對象語言,如果你學過java,c#等正統面向對象語言,你會難以理解js的面向對象,他和普通的面向對象不太一樣,今天,我們通過封裝一個toast插件,來看看js面向對象是如何運行的。

html

<div id="toast"></div>

css

* {
    margin: 0;
    padding: 0;
}

#toast {
    position: absolute;
    display: none;
    left: 50%;
    top: 50%;
    z-index: 99999;
    margin: 0 auto;
    -webkit-transform: translate(-50%);
    transform: translate(-50%);
    width: 50%;
    padding: 5px;
    border-radius: 5px;
    text-align: center;
    color: #fff;
    background-color: #000;
}

使用方法

var toast = new Toast("toast", "你好,對話框");
toast.show();

js核心代碼

 1 (function() {
 2     /***
 3      * 信息提示組件Toast v1.0
 4      * @param {Object} container 內容容器(必填)
 5      * @param {Object} content 文字內容(可選)
 6      * @param {Object} duration 顯示時長(可選)
 7      * 使用方法
 8      * var toast = new Toast("toast", "你好,對話框");
 9      * toast.show();(支持回調函數)
10      */
11     function Toast(container, content, duration) {
12         this.container = document.getElementById(container);
13         this.content = content || "這是一段對話";
14         this.duration = duration || 2000;
15     }
16 
17     Toast.prototype.show = function(callback) {
18         this.callback = callback || function() {};
19         this.container.style.opacity = 1;
20         this.container.style.display = "block";
21         this.container.innerHTML = this.content;
22 
23         setTimeout(function() {
24             this.callback && this.callback();
25             this.hide();
26         }.bind(this), this.duration);
27 
28         return this;
29     }
30 
31     Toast.prototype.hide = function(callback) {
32         this.callback = callback || function() {};
33 
34         this.container.style.display = "none";
35         this.callback && this.callback();
36         return this;
37     }
38 
39     window.Toast = Toast;
40 
41 })(window);

Toas函數是一個構造函數,相當於面向對象語言中的類(class),並且有形參,函數內部代碼相當於給成員變量賦值。通常在這里初始化成員變量,這就好理解了。接下里的show,hide方法都是在Toast上的原型上添加共有的方法,對應的是修飾詞為public的一個成員方法。函數最后都會返回this(當前函數執行的上下文),是為了可以進行鏈式調用。這些方法都支持回調函數,當函數執行完畢后會執行傳入的回調函數,這在編寫插件的時候通常都會用到,比如說ajax請求完成后,你得到返回的數據,並且需要后續操作,這時就要用回調函數。因為代碼都放在閉包環境下,外界訪問不了里面的變量和方法,所以把Toast強行暴露出去,就可以在window訪問到。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM