2013年10月9日 星期三

[JavaScript] 練習內定物件與函式: arguments, callee, caller, this, apply(), call()

  • callee
    此為arguments的屬性之一,可取得被call function本身。
  • caller
    可用來取得call該function的來源物件。
  • this
    指到函數的擁有者(Owner)。
  • apply()與call()
    apply與call兩者本身的功能相同,都可以用來特別指定被call function中的this變數。
    不同之處在於傳入參數的寫法不同:

    apply( thisArg, argArray ); // 第二個參數必須是個Array,否則會產生參數型態錯誤的Error
    call( thisArg[, arg1, arg2…] );

 var t = function(){ this.s = 1; log('========================'); log( arguments ); // 實際傳入的參數陣列 log( arguments.callee ); // 指到methodA log( arguments.callee.caller ); // 指到call methodA的object log( 'new Length: '+arguments.callee.length ); log( 'rellay length: '+arguments.length ); log( this.s ); this.a = function () { this.s = 2; this.len = arguments.length; log('========================'); log( arguments ); // 實際傳入的參數陣列 log( arguments.callee ); // 指到methodA log( arguments.callee.caller ); // 指到call methodA的object log( 'new lengt: '+arguments.callee.length ); log( 'rellay lengt: '+arguments.length ); log( this ); return this ; } this.get_s =function (){ log('========================'); log( arguments ); // 實際傳入的參數陣列 log( arguments.callee ); // 指到methodA log( arguments.callee.caller ); // 指到call methodA的object log( 'new lengt: '+arguments.callee.length ); log( 'rellay lengt: '+arguments.length ); log( this ); log(this.s); log(this.len); } } function log(msg) { if( window.console ) { console.log(msg); } } var a = new t(1,2,3,4) a.a(1,2,3); a.a.apply(window,['x','y']); log('len:'+a.len); 

log 結果:
========================
[1, 2, 3, 4]
function()
null
new Length: 0
rellay length: 4
1
========================
[1, 2, 3]
function()
null
new lengt: 0
rellay lengt: 3
Object { s=2, len=3, a=function(), 更多...}
========================
["x", "y"]
function()
null
new lengt: 0
rellay lengt: 2
Window t.html
len:3

來源參考:

【下列文章您可能也有興趣】

沒有留言: