B
B
BonBon Slick2020-04-22 10:11:25
JavaScript
BonBon Slick, 2020-04-22 10:11:25

When and how to declare objects?

1. Object constructor

var person = new Object();

person.name = "Anand",
person.getName = function(){
  return this.name ; 
};


2.literal constructor
var person = { 
  name : "Anand",
  getName : function (){
   return this.name
  } 
}


3. function constructor
function Person(name){
  this.name = name
  this.getName = function(){
    return this.name
  } 
}


4. Prototype
function Person(){};

Person.prototype.name = "Anand";


5.Function/Prototype combination
function Person(name){
  this.name = name;
} 
Person.prototype.getName = function(){
  return this.name
}


6.Singleton
var person = new function(){
  this.name = "Anand"
}


When, how, why?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Bogachev, 2020-04-22
@BonBonSlick

Vote for unspecified option #7: use classes (one per module) and never shaman anything on prototypes by hand. This will allow you to keep an understanding of what is happening in the code in general for a longer time.

export default class Person {
    constructor(name) {
        this.name = name;
    }

    getName() {
        return `My name is ${this.name}`;
    }
}

// Если нужен singleton, немного меняем экспорт:
//
// const PERSON = new Person();
// export default PERSON;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question