你怎么称呼本地功能? [英] How do you call a local function?

查看:126
本文介绍了你怎么称呼本地功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以继承人的基本概述

 函数x(){
//一些代码
函数y(){
//多一些代码
}
}

函数z(){
//如何调用函数y?

我试过了

 函数z(){
window [x] [y];




函数z(){
x(); y();
}

都不行!

 函数x(){
//一些代码
函数y(){
//多一些代码
}
}
$ b

上面在 x 中声明了 y ,所以它被创建为 x 每次调用 x 时的变量对象。除非 x 中的代码使它可以从别处获得,否则 只能从 x 内部访问。

 函数z(){
//我如何调用函数y?

要从 z中调用 y ,它必须在 z 的作用域链上可用。可以通过在函数调用中传递它(使其成为 z 的变量对象的属性),或者将它作为 z 的作用域上的某个对象的属性链。



如果函数可用于两个函数,那么声明它可以被 x z ,或以 y 可用的方式初始化 z 。例如

  var z; 
var x =(function(){
function y(){}
$ bz = function(){
//调用y的东西;
};

return function(){
// x function body
}
}());

在上文中, x z 都可以访问相同的 y 函数,并且每次调用 x 时都不会创建它。请注意,直到分配给 x 的代码被执行时, z 才会被定义。



y 仅适用于 x z ,它不能被任何其他函数访问(所以 y 可能被称为 private 函数, x z 可能被称为特权函数) / p>

So heres the basic outline

function x(){
   // some code 
   function y(){
   //some more code
  }
}

function z(){
  // how do i call function y?
}

I tried

function z(){
   window[x][y];
} 

and

function z(){
x();y();
}

neither works!

解决方案

Lots of code, not much explanation.

function x(){
   // some code 
   function y(){
   //some more code
  }
}

The above declares y inside x, so it is created as a property of x's variable object each time x is called. y can only be accessed from inside x unless code inside x makes it available from elsewhere.

function z(){
  // how do i call function y?
}

To call y from inside z, it must be available on z's scope chain. That can be done by passing it in the function call (making it a property of z's variable object) or making it a property of some object on z's scope chain.

If the function is to be available to both functions, it makes sense to declare it where it can be accessed by both x and z, or initialize z in such a manner that y is available. e.g.

var z;
var x = (function() {
  function y(){}

  z = function() {
        // something that calls y;
      };

  return function() {
    // x function body
  }
}());

In the above, x and z both have access to the same y function and it is not created each time x is called. Note that z will be undefined until the code assigning to x is executed.

Note also that y is only available to x and z, it can't be accessed by any other function (so y might be called a private function and x and z might be called privileged functions).

这篇关于你怎么称呼本地功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆