JavaScript访问调用函数中声明的变量

JavaScript accessing variables declared in calling function

本文关键字:声明 变量 函数 访问 调用 JavaScript      更新时间:2024-03-06

很难解释我的问题,所以我发布了一些代码。

function caller(func) {
    function printMessage(message) {
        console.log(message);
    }
    func();
}
function callee() {
    printMessage('hello world');
}
caller(callee);

我想从被调用者访问printMessage,但按照目前的情况,这会引发ReferenceError。如果可能的话,我希望避免在全局范围内声明printMessage。

您可以将要在callee内部使用的函数作为参数传递给callee;只要调用者可以访问,那么callee就不在乎它是在哪里定义的:

function caller(func) {
    ....
    func(printMessage);
}
function callee( func ) {
    func("hello world");
}

您可以做的一件事是让"caller"调用传递给它的函数,并打印返回值。

function caller(func) {
  function printMessage(message) {
    console.log(message);
  }
  printMessage(func());
}
function callee() {
  return 'hello world';
}
function callee2() {
  return 'hello world 2';
}
caller(callee);
caller(callee2);

编辑

在阅读了您对问题的评论后,这可能更适合OO方法,例如:

//--- Base 'libary' caller ---//
var caller = function() {
}
//--- Add out printMessage function to our base libary ---//
caller.prototype.printMessage = function(message){
    console.log(message);
}
//--- Users 'libary' callee ---//
var callee = function() {
    caller.call(this);
    //--- Our users libary has a printing function ---//
    this.print = function ( message ) {
        this.printMessage("callee > " + message);
    }
}
callee.prototype = Object.create(caller.prototype); // Set callee's prototype to caller's prototype
callee.prototype.constructor = callee; // Set constructor back to callee
//--- Using the users libary ---//
var userLibary = new callee();
userLibary.print("hello world"); // 'callee > hello world'
//--- The original libary's print method is still accessible ---//
userLibary.printMessage("hello world"); // 'hello world'

基本上,你不能。嵌套的printMessage仅限于caller范围。

您可以通过calee.caller原型访问caller构造函数,但它仅在调用方的作用域下"锁定"。。

仅供参考:

function caller(func) {
    function printMessage(message) {
        console.log(message);
    }
    func();
}
function callee() {
    //you can access the caller's constructor from prototype..
    var callerFunc = arguments.callee.caller.prototype;
    console.log(callerFunc);
    //you can get the actual code
    var code = arguments.callee.caller.toString();
    console.log(code);
    //but you can't invoke the nested function which is under
    //caller scope only...will throw ReferenceError
    printMessage('hello world');
}
caller(callee);

jsfiddle:http://jsfiddle.net/ufxnoaL1/

此外,请注意,arguments.callee将不受支持,也不应使用

警告:ECMAScript(ES5)第5版禁止使用arguments.callele()处于严格模式。通过避免使用arguments.callele()为函数表达式命名或使用函数函数必须调用自身的声明。

eval似乎相当优雅地实现了这一点。

function caller(func) {
    function printMessage(message) {
        console.log(message);
    }
    eval('(' + func.toString() + ')();');
}
function callee() {
    printMessage('hello world');
}
caller(callee);