javascript - this指针和闭包那个性能更好?
本文介绍了javascript - this指针和闭包那个性能更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
在编程的时候经常会遇到this指针和闭包同时存在的问题。如下面的代码所示。
【1】使用这两种方法都能解决问题,但是那个性能会更好些。怎么分析?
【2】在使用第二种方法中,使用了bind改变了this指针后,是否仍相对于test函数形成闭包?
<script>
function test() {
var obj = {name: 1};
window.setTimeout(function () {
console.log(obj.name);
}, 1000);
window.setTimeout(function () {
console.log(this.name);
}.bind(obj), 1000);
}
test();
</script>
解决方案
https://jsfiddle.net/hsfzxjy/xm46t186/
let obj = { name: 1 }
function func1 () {
obj.name = 2
}
let func2 = function () {
this.name = 2
}.bind(obj)
function test (func) {
let i
for (i = 0;i < 1000000; i++) func()
}
console.time('func1')
test(func1)
console.timeEnd('func1')
console.time('func2')
test(func2)
console.timeEnd('func2')
结果差异显著:
相关阅读:Why is bind slower than a closure?
这篇关于javascript - this指针和闭包那个性能更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文