一、控制给一个给定函数的作用域
1.1 使用bind()方法
<script>
window.onload = function () {
window.name = "window";
var data = {
name: "testObject",
sayOne: function () {
console.log("1111" + this.name);
sayTwo = function (type) {
console.log(type + " " + this.name);
};//.bind(this);
sayTwo("2222");
}
};
data.sayOne("****");
};
</script>
<script>
window.onload = function () {
window.name = "window";
var data = {
name: "testObject",
sayOne: function () {
console.log("1111" + this.name);
sayTwo = function (type) {
console.log(type + " " + this.name);
}.bind(this);
sayTwo("2222");
}
};
data.sayOne("****");
};
</script>
this关键字表示函数的所有者或作用域。
在该解决方案中,字面值对象的一个方法sayOne(),其中包含一个嵌套的sayTwo()函数。
没有使用bind()方法,打印出的消息大相径庭,原因在于,嵌套的函数与包围的对象的内部函数分离开了,并且无作用域的函数自动变成窗口对象的属性。bind()方法所做的就是,使用apply()方法把函数绑定到传递给对象的对象。使用bind()方法可将其绑定到父对象。
1.2 bind()与定时器
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="item">
20
</div>
<script>
var theCounter = new Counter('item', 20, 0);
theCounter.countDown();
function Counter(id, start, finish) {
this.str = this.start = start;
this.finish = finish;
this.id = id;
this.countDown = function () {
if (this.str == this.finish) {
this.countDown = null;
return;
}
document.getElementById(this.id).innerHTML = this.str--;
setTimeout(this.countDown.bind(this), 1000);
};
}
</script>
</body>
</html>
1.3 self与this
使用bind()的替代方法,就是将this赋值给外部函数中的一个变量,该变量随后在尾部可供使用。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="item">
20
</div>
<script>
var theCounter = new Counter('item', 20, 0);
theCounter.countDown();
function Counter(id, start, finish) {
var self = this;
this.str = this.start = start;
this.finish = finish;
this.id = id;
this.countDown = function () {
if (this.str == this.finish) {
this.countDown = null;
return;
}
document.getElementById(this.id).innerHTML = this.str--;
setTimeout(this.countDown.bind(self), 1000);
//setTimeout(this.countDown, 1000);//若没有bind(),当定时器内部调用该方法的时候,对象作用域和计数器已经丢失了
};
}
</script>
</body>
</html>