简体   繁体   English

在JavaScript中调用最内部函数的最佳方法

[英]Best way to call the inner most function in javascript

var f = function() {
   this.m = '10' ; 
   f1 = function(){
        alert(m)
    }
}

o = new f()
o.m

f1()

Is this the right way to call nested function f1 from the above example 这是从上面的示例中调用嵌套函数f1的正确方法吗

I am assuming you wanted f1 to be a method of f , in which case you need to add it as a property (as you've done for m ): 我假设您希望f1f的方法,在这种情况下,您需要将其添加为属性(就像对m所做的那样):

var f = function() {
   this.m = '10'; 
   this.f1 = function(){
       alert(this.m); //Notice that this has changed to `this.m`
   };
}; //Function expressions should be terminated with a semicolon

You can then call the method on an instance of f : 然后可以在f的实例上调用该方法:

o = new f();
o.f1(); //Alerts '10'

Here's a working example . 这是一个有效的例子

The way you have it currently will result in f1 leaking into the global scope (since it's declared without the var statement). 当前使用它的方式将导致f1泄漏到全局范围内(因为它是在没有var语句的情况下声明的)。


Side note: it's usually preferrable to make your methods properties of the prototype . 旁注:通常最好将方法的属性设为prototype This results in a single copy of the function in memory, instead of a copy for each instance: 这将在内存中生成该函数的单个副本,而不是每个实例的副本:

var f = function() {
   this.m = '10';
};

f.prototype.f1 = function() {
    alert(this.m);  
};

With your code, the function is an inner function and not callable from the outside. 对于您的代码,该函数是内部函数,不能从外部调用。 If you call it inside a constructor, you have to assign f1 to the object: 如果在构造函数中调用它,则必须将f1分配给该对象:

this.f1 = function() {
  alert(m);
}

Then you can call: 然后,您可以致电:

o = new f()
o.f1() //=> alerts 10

暂无
暂无

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

相关问题 哪个是在链接上调用javascript函数的最佳方法 - Which is the best way to call a javascript function on a link Javascript:最有效的方法是将变量定义为函数调用,或者将null定义为变量? - Javascript: Most effecient way to define variable to a function call, or if null to a variable? 等待Java中异步函数调用的最有效方法是什么? - What's the most efficient way to wait for an asynchronous function call in Javascript? 在另一个函数JavaScript / JQuery中调用函数的最佳方法? - Best way to call function inside of another function JavaScript/JQuery? Javascript:如何调用此内部函数? - Javascript: How to call this inner function? javascript函数调用计时。 实施此的最佳方法 - javascript function call timing. The best way of implementing this 想要模式以便在JavaScript中将函数参数传递给setTimeout调用的最佳方法 - wanting pattern for best way to pass function parameters into setTimeout call in JavaScript 从Java Applet调用JavaScript函数的最佳方法 - Best way to call a JavaScript function from an Java Applet 为什么我的async fetch调用一直返回或退出到最外面的function,执行外面的function,然后继续执行里面的? - Why does my async fetch call return or exit all the way to the most outer function, execute the outer function, THEN continue executing the inner one? 使用 JavaScript 调用 Node.js 后端函数的最有效方法是什么 - What's the most efficient way to call a Node.js backend function with JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM