求解面向对象中的call和prototype

zebds_regex 2017-03-15 01:59:25
问题在代码里
<head>
<style>
#div1{width:100px; height:100px; background:#CCC; position:absolute; left:0;}
</style>
<title>无标题文档</title>
<script>
function Drag(id)
{
var _this=this;
this.oDiv=document.getElementById(id);
this.disX=0;
this.disY=0;
this.oDiv.onmousedown=function(){
_this.fnDown();
return false;
};
}
Drag.prototype.fnDown=function(ev)
{
var _this=this;
var oEvent=ev||event;
this.disX=oEvent.clientX-this.oDiv.offsetLeft;
this.disY=oEvent.clientY-this.oDiv.offsetTop;
document.onmousemove=function(){
_this.fnMove();
};
document.onmouseup=function(){
_this.fnUp();
};
}
Drag.prototype.fnMove=function(ev)
{
var oEvent=ev||event;
this.oDiv.style.left=oEvent.clientX-this.disX+'px';
this.oDiv.style.top=oEvent.clientY-this.disY+'px';
}
Drag.prototype.fnUp=function()
{
document.onmousemove=null;
document.onmouseup=null;
}
//------------------------------------------------------
function LimitDrag(id)
{
Drag.call(this,id)
//我想知道call的作用是什么?是不是为了继承父类的属性?他的原理是什么?在这里用了call以后,LimitDrag能做什么(我意思是如果没有下面的代码,只有这一句,他已经实现了那部分的功能)?
}
for(var i in Drag.prototype)
{
LimitDrag.prototype[i]=Drag.prototype[i];
//原型链的作用又是什么?是不是为了继承父类的方法?
}
LimitDrag.prototype.fnMove=function(ev)
{
var oEvent=ev||event;
var l=oEvent.clientX-this.disX;
var t=oEvent.clientY-this.disY;
if(l<0)
{
l=0;
}
else if(l>document.documentElement.clientWidth-this.oDiv.offsetWidth)
{
l=document.documentElement.clientWidth-this.oDiv.offsetWidth;
}
if(t<0)
{
t=0;
}
else if(t>document.documentElement.clientHeight-this.oDiv.offsetHeight)
{
t=document.documentElement.clientHeight-this.oDiv.offsetHeight;
}
this.oDiv.style.left=l+'px';
this.oDiv.style.top=t+'px';
}
window.onload=function()
{
new LimitDrag('div1')
}
</script>
</head>

<body>
<div id="div1">
</div>
</body>
</html>
...全文
156 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
xiaojunjor 2017-03-15
  • 打赏
  • 举报
回复
引用 2 楼 xiaojunjor 的回复:
1#简单明了 我再加个API,可以看一看
<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call">call</a>,<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">原型链</a>
不要见笑,没用过这个,再试一下call原型链
xiaojunjor 2017-03-15
  • 打赏
  • 举报
回复
1#简单明了 我再加个API,可以看一看
<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call">call</a>,<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">原型链</a>
jiangbai333 2017-03-15
  • 打赏
  • 举报
回复
call 改变this指向! prototype 为了继承!

87,994

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧