Refer this:https://www.w3schools.com/js/js_object_definition.asp
Or
Or
There is various way to define a function. It is totally based upon your requirement. Below are the few styles :-
- Object Constructor
- Literal constructor
- Function Based
- Protoype Based
- Function and Prototype Based
- Singleton Based
Examples:
- Object constructor
var person = new Object();
person.name = "Anand",
person.getName = function(){
return this.name ;
};
- Literal constructor
var person = {
name : "Anand",
getName : function (){
return this.name
}
}
- function Constructor
function Person(name){
this.name = name
this.getName = function(){
return this.name
}
}
- Prototype
function Person(){};
Person.prototype.name = "Anand";
- Function/Prototype combination
function Person(name){
this.name = name;
}
Person.prototype.getName = function(){
return this.name
}
- Singleton
var person = new function(){
this.name = "Anand"
}
You can try it on console, if you have any confusion.
No comments:
Post a Comment