非严格模式下。this指向window
function a(){
console.log(this);
}
a();
当函数执行是,借助与call,apply我们能改变它内部的this指向
借助于call执行的时候:
第一个实参相当于函数的this指向
第二个实参对应于第一个形参
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{margin:0;padding: 0;}
#wrap{
width: 100px;
height: 100px;
background-color: pink;
}
#box{
width: 100px;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div id="wrap"></div>
<div id="box"></div>
<script>
var id = "window";
document.id = "document";
var oWrap = document.getElementById("wrap");
var oBox = document.getElementById("box");
//点击指向的是document的id
oWrap.onclick = function(){
a.call( document , 1);
}
//点击指向的是window的id
oBox.onclick = function(){
a( 2 );
}
function a(num){
console.dir( num + ":" + this.id );
}
</script>
</body>
</html>
var id = "window";
document.id = "document";
var oWrap = document.getElementById("wrap");
var oBox = document.getElementById("box");
//点击指向的是 oWrap
oWrap.onclick = function(){
a.call( this , 1);
}
//点击指向的是window的id
oBox.onclick = function(){
a( 2 );
}
function a(num){
console.dir( num + ":" + this.id );
}