前言
网上看到一句话,匿名函数的执行是具有全局性的,那怎么具有的全局性呢?
this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向的是那个调用它的对象
1.案例中,第一个say打出来的是Alan,而第二个则是window
var name = 'window'
var person = {
name :'Alan',
sayOne:function () {
console.log(this.name)
},
sayTwo:function () {
return function () {
console.log(this.name)
}
}
}
person.sayOne()//Alan
person.sayTwo()() // window
2.原因
3.我们也可以更改this指向,这里应用JS高级编程的案例
var name = "global";
var foo = {
name: "foo",
getName : function(){
console.log(this.name);
}
}
var bar = {
name: "bar",
getName : function(){
return (function(){
console.log(this.name);
})();
}
}
foo.getName(); //foo
foo.getName.call(bar); //bar
foo.getName.call(this); //global
foo.getName.call(window); //global
(function(){
console.log(this.name)
}.bind(bar))(); //bar
(function(){
console.log(this.name)
}.bind())(); //global
总结
Copyright © 2019- ucpa.cn 版权所有
违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务