用js面向对象思想封装插件

时间:2023-03-09 05:55:22
用js面向对象思想封装插件

js是基于原型的面向对象语言,如果你学过java,c#等正统面向对象语言,你会难以理解js的面向对象,他和普通的面向对象不太一样,今天,我们通过封装一个toast插件,来看看js面向对象是如何运行的。

html

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

css

* {
margin:;
padding:;
} #toast {
position: absolute;
display: none;
left: 50%;
top: 50%;
z-index:;
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核心代码

 (function() {
/***
* 信息提示组件Toast v1.0
* @param {Object} container 内容容器(必填)
* @param {Object} content 文字内容(可选)
* @param {Object} duration 显示时长(可选)
* 使用方法
* var toast = new Toast("toast", "你好,对话框");
* toast.show();(支持回调函数)
*/
function Toast(container, content, duration) {
this.container = document.getElementById(container);
this.content = content || "这是一段对话";
this.duration = duration || 2000;
} Toast.prototype.show = function(callback) {
this.callback = callback || function() {};
this.container.style.opacity = 1;
this.container.style.display = "block";
this.container.innerHTML = this.content; setTimeout(function() {
this.callback && this.callback();
this.hide();
}.bind(this), this.duration); return this;
} Toast.prototype.hide = function(callback) {
this.callback = callback || function() {}; this.container.style.display = "none";
this.callback && this.callback();
return this;
} window.Toast = Toast; })(window);

Toas函数是一个构造函数,相当于面向对象语言中的类(class),并且有形参,函数内部代码相当于给成员变量赋值。通常在这里初始化成员变量,这就好理解了。接下里的show,hide方法都是在Toast上的原型上添加共有的方法,对应的是修饰词为public的一个成员方法。函数最后都会返回this(当前函数执行的上下文),是为了可以进行链式调用。这些方法都支持回调函数,当函数执行完毕后会执行传入的回调函数,这在编写插件的时候通常都会用到,比如说ajax请求完成后,你得到返回的数据,并且需要后续操作,这时就要用回调函数。因为代码都放在闭包环境下,外界访问不了里面的变量和方法,所以把Toast强行暴露出去,就可以在window访问到。