[英]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()
这是从上面的示例中调用嵌套函数f1的正确方法吗
我假设您希望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
然后可以在f
的实例上调用该方法:
o = new f();
o.f1(); //Alerts '10'
这是一个有效的例子 。
当前使用它的方式将导致f1
泄漏到全局范围内(因为它是在没有var
语句的情况下声明的)。
旁注:通常最好将方法的属性设为prototype
。 这将在内存中生成该函数的单个副本,而不是每个实例的副本:
var f = function() {
this.m = '10';
};
f.prototype.f1 = function() {
alert(this.m);
};
对于您的代码,该函数是内部函数,不能从外部调用。 如果在构造函数中调用它,则必须将f1分配给该对象:
this.f1 = function() {
alert(m);
}
然后,您可以致电:
o = new f()
o.f1() //=> alerts 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.