Create new objects

  • Create a single object, using an object literal.
  • Create a single object, with the keyword new.
  • Define an object constructor, and then create objects of the constructed type.
  • Create an object using Object.create().
// using an object literal
var person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue" };
var person = {};
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
 
// with the keyword `new`
const person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";

Access Object Properties

objectName.property; // person.age
objectName["property"]; // person["age"]
objectName[expression]; // x = "age"; person[x]

for…in Loop

The block of code inside of the for...in loop will be executed once for each property.

const person = {
  fname: "John",
  lname: "Doe",
  age: 25,
};
 
let txt = "";
for (let x in person) {
  // x is properties key
  txt += person[x] + " ";
}
// txt is "John Doe 25".

Add or Delete Properties

person.nationality = "English";
delete person.nationality;
delete person["age"];

The delete keyword does not delete inherited properties, but if you delete a prototype property, it will affect all objects inherited from the prototype.

Nested Objects

myObj = {
  name: "John",
  age: 30,
  cars: {
    car1: "Ford",
    car2: "BMW",
    car3: "Fiat",
  },
};
 
myObj.cars.car2;
myObj.cars["car2"];
myObj["cars"]["car2"];

Object Method

const person = {
  firstName: "John",
  lastName: "Doe",
  id: 5566,
  fullName: function () {
    return this.firstName + " " + this.lastName;
  },
};

JS this 关键词

// get func return
name = person.fullName();
// get func
name = person.fullName;

Add Object Method

Method is also one type of object property.

person.name = function () {
  return this.firstName + " " + this.lastName;
};

Display Object

Default cant display object well.

document.getElementById("demo").innerHTML = person;
// [object Object]

Using Object.values(obj)

  • Any JavaScript object can be converted to an array using Object.values():
const person = {
  name: "John",
  age: 30,
  city: "New York",
  fullname: function () {
    return 2;
  },
};
const myArray = Object.values(person);
// John,30,New York,function() {return 2}

Using JSON.stringify(obj)

  • Any JavaScript object can be stringified (converted to a string) with the JavaScript function JSON.stringify().
  • It will converts dates into strings.
  • It will not stringify functions.
const person = {
  name: "John",
  age: 30,
  city: "New York",
  today: new Date(),
  fullname: function () {
    return 2;
  },
};
let myString = JSON.stringify(person);
// {"name":"John","age":30,"city":"New York","today":"2024-02-16T07:28:47.621Z"}

Getter & Setter

const person = {
  language: "en",
  get getLang() {
    // getLang is property
    return this.language;
  },
  set setLang(lang) {
    this.language = lang;
  },
  getLangFunc: function () {
    // getLangFunc is function
    return this.language;
  },
};
 
// get
var langValue = person.getLang;
// set
person.setLang = "en";
// before func
var langValue = person.getLangFunc();

Add Getter & Setter

The Object.defineProperty() method can also be used to add Getters and Setters:

const obj = { counter: 0 };
 
// Define setters and getters
Object.defineProperty(obj, "reset", {
  get: function () {
    this.counter = 0;
  },
});
Object.defineProperty(obj, "increment", {
  get: function () {
    this.counter++;
  },
});
Object.defineProperty(obj, "decrement", {
  get: function () {
    this.counter--;
  },
});
Object.defineProperty(obj, "add", {
  set: function (value) {
    this.counter += value;
  },
});
Object.defineProperty(obj, "subtract", {
  set: function (value) {
    this.counter -= value;
  },
});
 
// Play with the counter:
obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement;

Object Constructors

function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
  this.changeName = function (name) {
    this.lastName = name;
  };
}
 
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");

You Can Adding a Property or Method to an Object,
But Cant Adding a Property to a Constructor.

myFather.nationality = "English"; // OK
Person.nationality = "English"; // ERROR

Object Prototypes

All JavaScript objects inherit properties and methods from a prototype:

  • Date objects inherit from Date.prototype
  • Array objects inherit from Array.prototype
  • Person objects inherit from Person.prototype

The Object.prototype is on the top of the prototype inheritance chain:
Date objects, Array objects, and Person objects inherit from Object.prototype.

The JavaScript prototype property allows you to add new props & func to object constructors:

function Person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
}
 
Person.prototype.nationality = "English";
Person.prototype.name = function () {
  return this.firstName + " " + this.lastName;
};

Object Iterable

myNumbers = {};
myNumbers[Symbol.iterator] = function () {
  let n = 0;
  done = false;
  return {
    next() {
      n += 10;
      if (n == 100) {
        done = true;
      }
      return { value: n, done: done };
    },
  };
};
 
for (const num of myNumbers) {
  // Any Code Here
}
let iterator = myNumbers[Symbol.iterator]();
while (true) {
  const result = iterator.next();
  if (result.done) break; // Any Code Here
}

Sets Object

JS Object Sets

Maps Object

JS Object Maps

JavaScript ES5 Object Methods

Managing Objects

// Create object with an existing object as prototype
Object.create();
 
// Adding or changing an object property
Object.defineProperty(object, property, descriptor);
 
// Adding or changing object properties
Object.defineProperties(object, descriptors);
 
// Accessing Properties
Object.getOwnPropertyDescriptor(object, property);
 
// Returns all properties as an array
Object.getOwnPropertyNames(object);
 
// Accessing the prototype
Object.getPrototypeOf(object);
 
// Returns enumerable properties as an array
Object.keys(object);

Protecting Objects

// Prevents adding properties to an object
Object.preventExtensions(object);
 
// Returns true if properties can be added to an object
Object.isExtensible(object);
 
// Prevents changes of object properties (not values)
Object.seal(object);
 
// Returns true if object is sealed
Object.isSealed(object);
 
// Prevents any changes to an object
Object.freeze(object);
 
// Returns true if object is frozen
Object.isFrozen(object);

Changing Meta Data

writable: true; // Property value can be changed
enumerable: true; // Property can be enumerated
configurable: true; // Property can be reconfigured
Object.defineProperty(person, "language", { writable: false });
Object.defineProperty(person, "language", { enumerable: false });
// Changing a Property Value
Object.defineProperty(person, "language", { value: "NO" });
 
// Adding a Property
Object.defineProperty(person, "year", { value: "2008" });
 
// Listing All Properties
Object.getOwnPropertyNames(person); // Returns an array of properties
// Listing Enumerable Properties
Object.keys(person); // Returns an array of enumerable properties