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第三章的環境模型你就全懂了