In JavaScript, an object is a composite data type made of properties and methods. Properties are key-value pairs, and methods are properties whose values are functions.
Almost everything in JavaScript is either an object or can be treated like one.
const user = { name: "Tom", age: 20,};new Object()const user = new Object();user.name = "Tom";user.age = 20;In practice, object literals are usually preferred.
const user = { name: "Tom", age: 20 };
console.log(user.name);console.log(user["age"]);Dot notation is simpler. Bracket notation is useful when the property name is dynamic.
user.age = 21;user.city = "Tokyo";delete user.city;const key = "score";
const result = { [key]: 100,};"name" in user; // trueuser.hasOwnProperty("age"); // trueconst name = "Tom";const age = 20;
const user = { name, age };Objects can contain methods:
const user = { name: "Tom", sayHello() { console.log(`Hello, I am ${this.name}`); },};this keywordInside an object method, this usually refers to the object used to call the method.
user.sayHello();Understanding this is one of the key parts of understanding JavaScript objects.
JavaScript uses prototypes as a core inheritance mechanism.
If a property does not exist on the object itself, JavaScript looks for it on the prototype.
const animal = { eat() { console.log("eating"); },};
const dog = Object.create(animal);dog.bark = function () { console.log("woof");};
dog.eat(); // inherited from animaldog.bark();Property lookup follows the prototype chain upward until:
nullconstructorFunctions used as constructors expose a prototype object, and instances usually have access to a constructor reference through that prototype.
function User(name) { this.name = name;}
const user = new User("Tom");console.log(user.constructor === User); // trueObjects are central to JavaScript. To use them well, you should understand:
this behave