Javascript difference between function and constructor syntax? -


this question has answer here:

i have studied javascript litte while can't seem how spot difference if statement function or constructor. code constructor:

function book (pages, author) { this.pages = pages; this.author = author; } 

and simple function:

var cars = function(printcar){ console.log(blabla); }; 

however have seen in serveral tutorials(i.e codecademy) using constructor syntax making functions aswell. how possible?

there no syntactic difference. (user-defined) functions can called both function/method or constructor. whether it's function declaration or expression doesn't matter:

var book = function() { … }; function book() { … } var example = function() { … }; function example() { … }; 

however, naming functions encouraged, , there's no reason write var example = function() { … } when can use declaration. there cases though expression (which typically anonymous) required, or declarations invalid.

what , entirely determined body code. constructors typically set properties on this, methods well. constructors have no return statement, new operator implicitly returns created instance.

a convention distinguishing them constructor functions have capitalized name.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

jquery - Keeping Kendo Datepicker in min/max range -