_this 和this有什么不同吗?

bringtree 2016-11-14 10:20:57

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.cubeSon{
height: 50px;
width: 50px;
margin: 5px;
display: inline-block;
text-align: center;
vertical-align: middle;
background-color: red;
}
</style>
</head>
<body>
<div>
<input id = "inputNum">
<button id = "rightAddBtn">左撤入</button>
<button id = "leftAddBtn" >右撤入</button>
<button id = "leftOutBtn">左撤出</button>
<button id = "rightOutBtn">右撤出</button>
</div>
<div id = "cube"></div>
<script src="task6.js"></script>
</body>
</html>


var getNum = document.getElementById('inputNum');
var rightAdd = document.getElementById('rightAddBtn');
var leftAdd = document.getElementById('leftAddBtn');
var rightOut = document.getElementById('rightOutBtn');
var leftOut = document.getElementById('leftOutBtn');
var contain = document.getElementById('cube');

rightAdd.addEventListener('click',function addnumR() {
var num = getNum.value;
contain.innerHTML ="<div class=\"cubeSon\"onclick=\"remove(this)\">"+num+"<\/div>"+contain.innerHTML;
});
leftAdd.addEventListener('click',function addnumL() {
var num = getNum.value;
contain.innerHTML =contain.innerHTML+ "<div class=\"cubeSon\"onclick=\"remove(this)\">"+num+"<\/div>";
});
rightOut.addEventListener('click',function removeR() {
contain.removeChild(contain.lastChild);
});
leftOut.addEventListener('click',function removeL() {
contain.removeChild(contain.firstChild);
});

function remove( _this ) {
alert(_this.innerHTML);
_this.remove();
}


当我把_this改成this的时候报错了。 想问下为什么要用_this ?什么情况下用?作用呢?
...全文
243 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
未知数 2016-11-15
  • 打赏
  • 举报
回复
引用 2 楼 bringtree 的回复:
[quote=引用 1 楼 zzgzzg00 的回复:] this是个关键字 只执行上下文 你的_this是个参数 两者完全没关系
平时不都是
function remove( ) {
  alert(this.innerHTML);
  this.remove();
}
吗 ? 为什么 这里就不可以呢?这里的this为什么指向了 window ? 别人说谁调用 this ,this 就指向谁。这里是点击div 的时候发生的,是div搞的事情 为什么this没指向他?[/quote] 你这儿html中写入的事件代码,dom处理结果是 dom.onclick=function(){remove(this)},该function下this指向dom,但remove不是事件函数了,remove内this指向window。这样写可以让remove中this指向dom <div class=\"cubeSon\"onclick=\"remove.apply(this,arguments)\">"
bringtree 2016-11-14
  • 打赏
  • 举报
回复
引用 1 楼 zzgzzg00 的回复:
this是个关键字 只执行上下文 你的_this是个参数 两者完全没关系
平时不都是
function remove( ) {
  alert(this.innerHTML);
  this.remove();
}
吗 ? 为什么 这里就不可以呢?这里的this为什么指向了 window ? 别人说谁调用 this ,this 就指向谁。这里是点击div 的时候发生的,是div搞的事情 为什么this没指向他?
似梦飞花 2016-11-14
  • 打赏
  • 举报
回复
this是个关键字 只执行上下文 你的_this是个参数 两者完全没关系

87,904

社区成员

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

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