[英]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
): 我假设您希望
f1
是f
的方法,在这种情况下,您需要将其添加为属性(就像对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.