Function 可用來建立函式物件。請注意大寫的 F,請勿與 function 混淆。在 javascript 中,所有物件都會繼承 Function 的特徵與方法。事實上,系統預設的物件,都繼承以下特徵與方法。
prototype | caller | constructor | length | name | apply |
call | toSource | toString | valueOf |
此特徵配合物件型態 Function 使用,可以增加物件的特徵與方法。
- 程式用法:
<script type='text/javascript'>
var aFunc=Function('x','document.write( "函式 : "+x)');
Function.prototype.newMethod=function ()
{
document.write( "新方法" +"<br />");
}
aFunc.newMethod();
document.write( aFunc.prototype );
</script> - 執行結果:
新方法
[object Object]
存有呼叫此函式的函式位置。
- 程式用法:
<script type='text/javascript'>
var callMe=Function('document.write( "誰叫我:"+ callMe.caller +"<br />")');
callMe();
function callOut()
{
callMe();
}
callOut();
</script> - 執行結果:
誰叫我:function dumpSample(id) { var obj=document.getElementById(id); /*** var p="padding:4px; line-height:100%; font-family:courier new; font-weight:bord; width:"+ Math.floor(screen.width/2+50) +"px; overflow:auto; background:#227722; white-space:nowrap"; ***/ var p="padding:4px 4px 40px; line-height:100%; font-family:courier new; font-weight:bord; width:90%; overflow:auto; background:#272; white-space:nowrap"; document.write('
- 程式用法:
'); var s,t; if(obj.textContent != undefined) { // FF, Safari, Chrome s=obj.textContent; // Blog 不能用 < 要用 \074 t=s.replace( /\074/g, '<').replace(/\n/g, '
'); } else { // IE s=obj.innerText; t=s.replace( /\074/g, '<').replace(/\r\n/g, '
'); } document.write(t.replace(/\s/g, ' ')); document.write(' - 執行結果:
'); document.write(s+'
誰叫我:function callOut() { callMe(); }
- 程式用法:
- Chrome 執行上例,會出錯。IE, Firefox, Safari 都能成功執行。
存有產生物件實體的函式其位置。
- 程式用法:
<script type='text/javascript'>
var sum=new Function('a,b,c',
'document.write( a+b+c )');
sum(1,2,3);
document.write( '<br />'+ sum.constructor );
</script> - 執行結果:
6
function Function() { [native code] }
存有參數的個數。
- 程式用法:
<script type='text/javascript'>
document.write( sum.length );
</script> - 執行結果:
3
存有函式的名稱。
- 程式用法:
<script type='text/javascript'>
document.write( sum.name +'<br />');
document.write( callOut.name );
</script> - 執行結果:
anonymous
callOut
- Firefox, Chrome 有支援; IE, Safari 無此項。
此法可用來繼承物件。請參考物件繼承。
此法可用來繼承物件。請參考物件繼承。
此法傳回物件實體的源碼。只有 Firefox 支援;IE, Safari, Chrome 無此項。
- 程式用法:
<script type='text/javascript'>
document.write( sum.toSource() );
</script> - 執行結果:
此法傳回物件實體的字串。
- 程式用法:
<script type='text/javascript'>
document.write( sum.toString() );
</script> - 執行結果:
function anonymous(a,b,c ) { document.write( a+b+c ) }
此法傳回存有函式源碼的字串。
- 程式用法:
<script type='text/javascript'>
document.write( sum.valueOf() );
</script> - 執行結果:
function anonymous(a,b,c ) { document.write( a+b+c ) }