bind用法
let info = { name: "xuhaitao", age: 36 }
function haitao() {
console.log(this);
}
let fun = haitao.bind(info)
fun();
haitao();
控制台打印:
闭包用法:
function xiaoMing() {
let v = 1;
function jia() {
v++;
console.log(v);
}
function getV() {
console.log(v);
}
return { jia: jia, getV: getV }
}
let x01 = xiaoMing();
x01.jia(); //2
x01.jia(); //3
x01.jia(); //4
x01.getV(); //4
let x02 = xiaoMing();
x02.jia(); //2
x02.jia(); //3
x02.jia(); //4
x02.getV(); //4
通过下面是实验,发现两个:
1 返回的方法放入数组中,然后遍历执行数组中的方法,发现this变成了数组
2 闭包仍然存在
<script type="text/javascript">
function xiaoMing() {
let aa = { name: "jia011", age: 3338 };
function show() {
console.log(aa.name, aa.age);
console.log(this);
printt();
}
function printt() {
console.log(aa.name, aa.age);
}
return { show: show }
}
function xiaoHong() {
let aa = { name: "jia022", age: 2223 };
function show() {
console.log(aa.name, aa.age);
console.log(this);
printt();
}
function printt() {
console.log(aa.name, aa.age);
}
return { show: show }
}
let obj01 = xiaoMing();
let obj02 = xiaoHong();
console.log("++++++++++++++++++++++++++++++++++++++++++")
var shuzu = [];//创建一个数组,用于保存各返回对象的方法
shuzu.push(obj01.show);
shuzu.push(obj02.show);
for (var i = 0; i < shuzu.length; i++) {
shuzu[i]();
console.log("++++++++++++++++++++++++++++++++++++++++++")
}
</script>
为了让this指向返回的对象,可以做如下修改
打印结果:
FR:徐海涛(hunk Xu)