一道小面試題

來源:互聯網
上載者:User
關鍵字 php
var obj1 = {name : "blue",fn : function(){alert(this.name);}};var newFunction = obj1.fn;newFunction();

為啥alert的是空,確不是undefined ?

回複內容:

var obj1 = {name : "blue",fn : function(){alert(this.name);}};var newFunction = obj1.fn;newFunction();

為啥alert的是空,確不是undefined ?

(1)this跟調用者有關,而不是和定義的位置有關,var newFunction = obj1.fn;這句話建立了fn的一個引用叫newFunction,而不是obj.fn,這裡原來fn就脫離了obj1,所以調用的範圍是window,這樣就讀不到obj1.name了
(2)name在window中有定義,如果在跨域中經常會修改這個屬性,所以window.name存在而且為空白,不是undefined

建議閱讀you don't know js這一系列書,特別講解了this範圍的四個判據,其中有例子就提到了什麼寫法會導致類中的函數脫離原有範圍

js 的this是當前{}吧

玩一下這個就清楚了

var obj1 = {name: 'blue', fn : function(){alert(this.name);}}; obj1.fn();    var newFunction = obj1.fn;newFunction();    //----------------------------------------------------    var obj2 = {here_do_not_use_name_as_var_name: 'blue',fn : function(){alert(this.here_do_not_use_name_as_var_name);}}; obj2.fn();    var newFunction2 = obj2.fn;newFunction2();        

function 有自己的 name

see also: http://www.w3schools.com/js/js_reserved.asp

去看下SICP第三章的環境模型你就全懂了

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.