js给window添加(替代)全局方法

面试的时候面试官让我用js手写封装一个alert方法,替代之前的alert,后面自己经过思索改造进行记录

为全局添加方法
  1. 方法一:(简单直观)
    window.a = function(){ ...  }
    window.alert = function(){ ...  }
    
  2. 方法2(利用jq的extend方法)
    $.extend(window,{
    	a:function(){ ... },
    	alert:function(){ ... }
    })
    
  3. 方法三(利用js)
    (()=>{
    	var defining = {
    		a:function(){ ... },
    		alert:function(){ ... }
    	}
    })
    Object.keys[defining].forEach(key=>{
    	window[key] = defining[key]
    })
    
  4. 方法四(window下的对象是变量的时候)
    window[a] = function(){ ... }
    
alert方法
var myAlert = {
	alertbox: function(alertContent) {
		var windowWidth = window.innerWidth;
		windowHeight = window.innerHeight;
		alertContainer = document.createElement("div");
		alertContainer.id = "myAlertBox";
		alertContainer.style.cssText = "position:absolute;left:0px;top:0px;width:100%;z-index:9999;";
		alertContainer.style.height = windowHeight + "px";
		alertOpacity = document.createElement("div");
		alertOpacity.style.cssText =
			"position:absolute;left:0px;top:0px;width:100%;background:#000;opacity:0.5;z-index:9999;";
		alertOpacity.style.height = windowHeight + "px";
		alertContainer.appendChild(alertOpacity)
		alertMainBox = document.createElement("div");
		alertMainBox.style.cssText =
			"position:absolute;width:200px;height:200px;line-height:200px;text-align:center;background:green;z-index:10000;"
		alertMainBoxLeft = (windowWidth - 200) / 2;
		alertMainBoxTop = (windowHeight - 200) / 2;
		alertMainBox.style.left = alertMainBoxLeft + "px";
		alertMainBox.style.top = alertMainBoxTop + "px";
		alertMainBox.innerHTML = alertContent;
		alertContainer.appendChild(alertMainBox);
		alertClose = document.createElement("div");
		alertClose.id = "closeBox";
		alertClose.style.cssText =
			"position:absolute;right:0px;top:0px;width:30px;height:30px;background:red;cursor:pointer";
		alertMainBox.appendChild(alertClose);
		document.body.appendChild(alertContainer);
		closeButton = document.getElementById("closeBox");
		console.log(closeButton)
		closeButton.onclick = function() {
			document.body.removeChild(document.getElementById("myAlertBox"));
		}
	}
}

myAlert.alertbox("这是自定义alert框");

alert里面可以定义多种方法,可以进行优化,将方法绑定到window就可以代替全局alert使用

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值