简体   繁体   中英

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

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 ):

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 :

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).


Side note: it's usually preferrable to make your methods properties of the 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:

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

Then you can call:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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