简体   繁体   English

如何在不外部返回内部的情况下访问内部函数

[英]How to access function inside function without outer returning inner one

I have got a function 'alpha', and there is another function 'beta' inside it. 我有一个函数“ alpha”,里面还有另一个函数“ beta”。 If I don't return beta in alpha, then how to access beta. 如果我不返回alpha测试版,那么如何访问beta。 Is there anyway of doing this? 反正有这样做吗? (Like, I can access alpha writing window.alpha(), as in global context alpha becomes a property of window object, then how to access beta as property, via window dom tree)? (就像,我可以访问alpha编写window.alpha(),因为在全局上下文中alpha成为窗口对象的属性,然后如何通过窗口dom树将beta作为属性访问)?

 <html> <head></head> <body> <script> function alpha() { console.log("hi"); function beta() { console.log("hello"); } } alpha(); //works window.alpha(); //works beta(); //it is directly not accessible. How to access it if alpha does not return it </script> </body> </html> 

alpha() is in Window Dom but why not beta? alpha()在Window Dom中,但为什么不是beta? (Even not inside alpha) (即使不在alpha内)

在此处输入图片说明

Normally you can not do this thing either you can prefer these option but in these you have to call alpha once in order to get beta 通常,您不能执行此操作,或者您更喜欢这些选项,但是在这些操作中,您必须调用一次alpha才能获得beta

//first option //第一个选项

(function alpha() { 
  console.log("hi");
  function beta() {
    console.log("hello");
  } 
  window.beta = beta;
})() 

//second option //第二个选项

Use this to create beta as property in alpha 使用this来创建beta作为alpha属性

function alpha() {
  this.beta = function() {
    console.log("hello");
  }
}
let alphaObject = new alpha();
alphaObject.beta();

If you don't want to return beta , you could return this and define beta as this.beta : 如果您不想返回beta ,则可以返回this并将beta定义为this.beta

To access beta() , you simply need to call alpha().beta() . 要访问beta() ,您只需要调用alpha().beta()

 function alpha() { console.log("hi"); this.beta = () => { console.log("hello"); } return this; } alpha().beta(); 

The beta() method is private to function alpha. beta()方法专用于功能alpha。 The way Javascript scoping works prevents you from directly accessing the inner functions . Javascript范围定义的工作方式可防止您直接访问内部函数。 Create it as a property of alpha by using this.beta 使用this.beta其创建为alpha的属性

Declare beta as a member of alpha using this : 使用this beta声明为alpha成员:

 function alpha() { console.log("hi"); this.beta = function() { console.log("hello"); } } let a = new alpha(); a.beta(); 

You current implementation prevents JavaScript from accessing beta from outside of alpha . 您当前的实现阻止JavaScript从alpha之外访问beta Read more about private functions in JavaScript. 阅读有关JavaScript中私有函数的更多信息。

Using this you can actually attach such methods to the instances of the function alpha . 使用this方法,您实际上可以将这些方法附加到函数alpha的实例。 That's what I've done in this solution. 这就是我在此解决方案中所做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM