当函数用new用健字调用的时候,那么函数默认返回值为this.
//定义一个变量来接收函数
let Fun = function(){
this.n="abc"
}
Fun.prototype.say = function(){
console.log(this.n)//谁调用我的函数我就指向学
}
//用来接收 Fun函数的结果 res又为实例对象 且构造函数是指向实例对象的
//那么res的值与this的值一样;
let res = new Fun()
console.log(res)//Fun {n: 'abc'}
res.say()//abc
拖拽的案例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 0px;
top: 0px;
cursor: move;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
<script>
//创建对象
function tuoZhuai(ele){
//获取事件
this.ele = document.querySelector('.box');
this.init();
}
//用原型对象创建一个函数init
tuoZhuai.prototype.init = function(){
//当鼠标按下的时候开始拖拽
this.ele.onmousedown = ()=>{
//光标的位置 事件处理
window.onmousemove = (e)=>{
this.left = e.clientX;
this.top = e.clientY;
this.move();
};
};
//当光标不在盒子中停止移动
window.onmouseup = function(){
window.onmousemove= null;
};
}
tuoZhuai.prototype.move = function(){
//事件对象
let x = this.left - this.ele.offsetWidth/2;
let y = this.top - this.ele.offsetHeight/2;
//最小边界值
let minX = 0 , minY = 0;
//最大边界值
let maxX = innerWidth - this.ele.offsetWidth;
let maxY = innerHeight - this.ele.offsetHeight;
//中间值x与最大值和最小值比较
x = Math.max(x,minX)
x = Math.min(x,maxX)
y = Math.max(y,minY)
y = Math.min(y,maxY)
this.ele.style.left = x + 'px';
this.ele.style.top = y +'px';
}
//new 一个实例对象
new tuoZhuai('.box');
</script>
</html>