標籤

ASP.NET MVC (29) Visual C# (15) JQuery (10) Plugins (8) JQuery Plugins (6) JavaScript (6) MySQL (5) CSS (4) LinQ (4) Mac OS (4) CentOS (3) Design Pattern (3) Entity Framework (3) IIS (3) Python (3) Windows (3) php (3) Docker (2) LAMP (2) SQL Server (2) WCF (2) .NET (1) .NET Core (1) AWS (1) Browser (1) GIS (1) IE (1) Internet Security (1) Linux (1) Platform (1) React (1) SEO (1) Testing (1) VMware (1) Windows 7 (1) cookie (1) curl (1) laravel (1) phpBB (1) session (1) 中古屋 (1) 透天 (1) 閒言閒語 (1) 面試 (1) 鳥松 (1)

2014年2月6日 星期四

[JavaScript] JavaScript考題

請問以下代碼運行結果為何?

function foo(){
foo.abc = function(){alert('def')}
this.abc = function(){alert('xyz')}
abc = function(){alert('@@@@@')};
var abc = function(){alert('$$$$$$')}
}
foo.prototype.abc = function(){alert('456');}
foo.abc = function(){alert('123');}
var f = new foo();
f.abc();
foo.abc();
abc();


 輸出為:
alert('xyz')
alert('def')


解釋:
var f = new foo(); 
//新建了一個foo對象,注意這時個上下文環境到了foo()中

f.abc();
//查找這個對象的abc()方法,輸出xyz,注意如果找不到就會去f.prototype裡找,到那時才會輸出456

foo.abc();
//在foo()中找到abc()方法,輸出def, 如果找不到會跳出foo() 到外面找到abc,輸出123

abc();
//在window中找到abc()方法,ie拋錯


 [Reference]
  http://jsfiddle.net/eMHY3/
  http://www.iteye.com/topic/268801

----------------------------------------------------
var b = function(b){ alert(b); }( function(){ alert(2); return '3'; }() );

結果為 ->2 ->3


沒有留言:

張貼留言