Different ways of writing javascript function
The examples below are different ways of writing a javascript function. The all have a property name and a method speak.
Regular Function.
function Person (name) { this.name=name; this.speak = function() { console.log("My name is "+name ); } } var p1 = new Person("Anna"); p1.speak();
Variable function.
var Person = function(name) { this.name=name; this.speak = function() { console.log("My name is "+name ); } } var p2 = new Person("Ben"); p2.speak();
Create an empty function and then assign property and method by using the object’s prototype property.
var Person = function(){}; Person.prototype.name; Person.prototype.speak = function() { console.log("My name is "+ this.name); } var p3 = new Person(); p3.name="Cain"; p3.speak();
Object literal, makes it a singleton object.
var Person = { name : "Dale", speak : function(){console.log("My name is "+this.name);} } Person.speak();
Create an object by using the keyword new, makes it a singleton object.
var Person = new function() { this.name = "Ean"; this.speak = function(){console.log("My name is "+this.name);} } Person.speak();
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts