Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Object.create()

The Object.create() method creates a new object based on an existing object as its prototype.

Example

// Create an Object:
const person = {
  firstName: “John”,
  lastName: “Doe”
};

// Create new Object
const man = Object.create(person);
man.firstName = “Peter”;

Object.keys()

The Object.keys() method returns an array containing the keys of an object.

Example

// Create an Object
const person = {
  firstName: “John”,
  lastName: “Doe”,
  age: 50,
  eyeColor: “blue”
};

// Get the Keys
const keys = Object.keys(person);

Object Management

ES5 introduced new methods for managing objects in JavaScript.

Managing Objects

// Adding or changing an object property
Object.defineProperty(object, property, descriptor)

// Adding or changing object properties
Object.defineProperties(object, descriptors)

// Accessing a Property
Object.getOwnPropertyDescriptor(object, property)

// Accessing Properties
Object.getOwnPropertyDescriptors(object)

// Returns all properties as an array
Object.getOwnPropertyNames(object)

// Accessing the prototype
Object.getPrototypeOf(object)

Object Protection

ES5 introduced methods for object protection in JavaScript.

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)

Function Bind()

The bind() method allows an object to borrow a method from another object.

 

In this example, two objects are created: person and member. The member object borrows the fullname method from the person object.

Example

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

const member = {
  firstName:“Hege”,
  lastName: “Nilsen”,
}

let fullName = person.fullName.bind(member);

Trailing Commas

ES5 permits trailing commas in object and array definitions.

Object Example

person = {
  firstName: “John”,
  lastName: ” Doe”,
  age: 46,
}

Array Example

points = [
  1,
  5,
  10,
  25,
  40,
  100,
];

JSON Objects:

// Allowed:
var person = ‘{“firstName”:”John”, “lastName”:”Doe”, “age”:46}’
JSON.parse(person)

// Not allowed:
var person = ‘{“firstName”:”John”, “lastName”:”Doe”, “age”:46,}’
JSON.parse(person)

JSON Arrays:

// Allowed:
points = [40100152510]

// Not allowed:
points = [40100152510,]