前言
網上看到一句話,匿名函數的執行是具有全局性的,那怎么具有的全局性呢?
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
總結
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com