Tuesday, 23 June 2015

javascript basic again -- function




function caller




var xello = function ()
{
    alert("CALL FROM: " + arguments.callee.caller.toString());
}

!function(){
xello();
}();

it will print out the last self executed function.

if you call xello() directly (without the self executing function), the caller is null, you will get null point exception. because xello is get called from global scope.

so the better code is:

unction myFunc() {
  if (myFunc.caller == null) {
    return 'The function was called from the top!';
  } else {
    return 'This function\'s caller was ' + myFunc.caller;
  }
}


"If the function f was invoked by the top level code, the value of f.caller is null, otherwise it's the function that called f." from "  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller



No comments:

Post a comment