use JavaScript functions to create simple objects code example

Example 1: creating an object javascript

let obj = {
// fields
  name:"value",
  num: 123,
//methods
  foo: function(){}
  
}

Example 2: how to create a object in javascript

var about = {
  name:"lanitoman",
  age:1023,
  isHeProgrammer:true
}

Example 3: create new object from existing object javascript

// With ES6 CLASSES
class User {
   constructor(firstName, lastName, dateOfBirth) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.dateOfBirth = dateOfBirth;

      this.getName = function(){
          return "User's name: " + this.firstName + " " + this.lastName;
      }
   }
}

var user001 = new User("John", "Smith", 1985);

// With Object.create()
var user001 = {
   firstName: "John",
   lastName: "Smith",
   dateOfBirth: 1985,
   getName: function(){
      return "User's name: " + this.firstName + " " + this.lastName;
   }
};

var user002 = Object.create(user001);
    
user002.firstName = "Jane";
user002.lastName = "King";
user002.dateOfBirth = 1989;

Tags:

Java Example