difference on javascript constructors -


is there difference between these 2 apart resolving constructor?

var person = function(living, age, gender) {     this.living = living;     this.age = age;     this.gender = gender;     this.getgender = function() {         return this.gender;     }; };  var person = function person(living, age, gender) {     this.living = living;     this.age = age;     this.gender = gender;     this.getgender = function() {         return this.gender;     }; }; 

both invoked using

var p = new person("yes",25,"male"); 

the first 1 resolves function() latter resolves person(), know if there advantage of using 1 on other

they identical purposes speak of.

the difference inside second function have clean reference function within itself.

formally

the language specification states:

functionexpression :

function identifier(opt) ( formalparameterlistopt ) { functionbody }

the identifier (in case person) in function expression optional

the reasoning explained bit later in language specification:

note identifier in functionexpression can referenced inside functionexpression's functionbody allow function call recursively. however, unlike in functiondeclaration, identifier in functionexpression cannot referenced , not affect scope enclosing functionexpression.

in practice

you can use second option in 2 situations:

when makes code more understandable:

   (function removebodydivs(){         //does logic removing         //divs body    })(); 

can more understandable than:

   (function (){         //does logic removing         //divs body    })(); 

when doing recursion, example

  var f = function fib(n){       return n<2?2:(fib(n-1)+fib(n-2));   } 

Comments

Popular posts from this blog

user interface - Python attempting to create a simple gui, getting "AttributeError: 'MainMenu' object has no attribute 'intro_screen'" -

jquery - Common JavaScript snippet to share files on Google Drive, Dropbox, Box.net or SkyDrive -

Android Gson.fromJson error -