this 关键字 主要用于函数中 不同的场景下 指向不同
function fn(){
console.log(this);
}
fn();
var btn = document.querySelector('button');
btn.onclick = function(){
console.log(this);
}
setInterval(function(){
console.log(this);
},1000);
var btn = document.querySelector('button');
btn.onclick = function(){
var _this = this;
setInterval(function(){
console.log(_this);
},1000);
}
var obj ={
name:"小明",
act:function(){
console.log(this.name);
},
c:{
name:"小红",
b:function(){
console.log(this.name);
}
}
}
obj.act();
obj.c.b();
call() apply() bind() 可以改变this在函数中的指向
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
function fn(){
console.log(this);
console.log( arguments );
}
fn.call(2,3,4,5,6);
function fn(){
console.log(this);
console.log( arguments );
}
fn.apply(2,[3,4,5,6]);
</script>
</body>
</html>
bind方法
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
function fn(){
console.log(this);
}
var fn2 = fn.bind(2);
fn2();
</script>
</body>
</html>