Javascript create object with methods

JavaScript Objects: Create Objects, Access Properties & Methods

Here you will learn objects, object literals, Object() constructor function, and access object in JavaScript.

You learned about primitive and structured data types in JavaScript. An object is a non-primitive, structured data type in JavaScript. Objects are same as variables in JavaScript, the only difference is that an object holds multiple values in terms of properties and methods.

In JavaScript, an object can be created in two ways: 1) using Object Literal/Initializer Syntax 2) using the Object() Constructor function with the new keyword. Objects created using any of these methods are the same.

The following example demonstrates creating objects using both ways.

var p1 = < name:"Steve" >; // object literal syntax var p2 = new Object(); // Object() constructor function p2.name = "Steve"; // property 

Above, p1 and p2 are the names of objects. Objects can be declared same as variables using var or let keywords. The p1 object is created using the object literal syntax (a short form of creating objects) with a property named name . The p2 object is created by calling the Object() constructor function with the new keyword. The p2.name = «Steve»; attach a property name to p2 object with a string value «Steve» .

Читайте также:  Mongodb tutorial for java

Create Object using Object Literal Syntax

The object literal is a short form of creating an object. Define an object in the < >brackets with key:value pairs separated by a comma. The key would be the name of the property and the value will be a literal value or a function.

The following example demonstrates objects created using object literal syntax.

var emptyObject = <>; // object with no properties or methods var person = < firstName: "John" >; // object with single property // object with single method var message = < showMessage: function (val) < alert(val); >>; // object with properties & method var person = < firstName: "James", lastName: "Bond", age: 15, getFullName: function () < return this.firstName + ' ' + this.lastName > >; 

Note that the whole key-value pair must be declared. Declaring only a key without a value is invalid, as shown below.

Create Objects using Objects() Constructor

Another way of creating objects is using the Object() constructor function using the new keyword. Properties and methods can be declared using the dot notation .property-name or using the square brackets [«property-name»] , as shown below.

var person = new Object(); // Attach properties and methods to person object person.firstName = "James"; person["lastName"] = "Bond"; person.age = 25; person.getFullName = function () < return this.firstName + ' ' + this.lastName; >; 

An object can have variables as properties or can have computed properties, as shown below.

var firstName = "James"; var lastName = "Bond"; var person =

Access JavaScript Object Properties & Methods

An object’s properties can be accessed using the dot notation obj.property-name or the square brackets obj[«property-name»] . However, method can be invoked only using the dot notation with the parenthesis, obj.method-name() , as shown below.

var person = < firstName: "James", lastName: "Bond", age: 25, getFullName: function () < return this.firstName + ' ' + this.lastName > >; person.firstName; // returns James person.lastName; // returns Bond person["firstName"];// returns James person["lastName"];// returns Bond person.getFullName(); // calling getFullName function 

In the above example, the person.firstName access the firstName property of a person object. The person[«firstName»] is another way of accessing a property. An object’s methods can be called using () operator e.g. person.getFullName() . JavaScript engine will return the function definition if accessed method without the parenthesis.

Accessing undeclared properties of an object will return undefined. If you are not sure whether an object has a particular property or not, then use the hasOwnProperty() method before accessing them, as shown below.

var person = new Object(); person.firstName; // returns undefined if(person.hasOwnProperty("firstName"))

The properties and methods will be available only to an object where they are declared.

var p1 = new Object(); p1.firstName = "James"; p1.lastName = "Bond"; var p2 = new Object(); p2.firstName; // undefined p2.lastName; // undefined p3 = p1; // assigns object p3.firstName; // James p3.lastName; // Bond p3.firstName = "Sachin"; // assigns new value p3.lastName = "Tendulkar"; // assigns new value 

Enumerate Object’s Properties

Use the for in loop to enumerate an object, as shown below.

var person = new Object(); person.firstName = "James"; person.lastName = "Bond"; for(var prop in person)< alert(prop); // access property name alert(person[prop]); // access property value >; 

Pass by Reference

Object in JavaScript passes by reference from one function to another.

function changeFirstName(per) < per.firstName = "Steve"; > var person = < firstName : "Bill" >; changeFirstName(person) person.firstName; // returns Steve 

Nested Objects

An object can be a property of another object. It is called a nested object.

var person = < firstName: "James", lastName: "Bond", age: 25, address: < id: 1, country:"UK" > >; person.address.country; // returns "UK" 

Points to Remember :

  1. JavaScript object is a standalone entity that holds multiple values in terms of properties and methods.
  2. Object property stores a literal value and method represents function.
  3. An object can be created using object literal or object constructor syntax.
  4. Object literal:
var person = new Object(); person.firstName = "James"; person["lastName"] = "Bond"; person.age = 25; person.getFullName = function () < return this.firstName + ' ' + this.lastName; >;

Источник

JavaScript Objects

In JavaScript, objects are king. If you understand objects, you understand JavaScript.

In JavaScript, almost «everything» is an object.

  • Booleans can be objects (if defined with the new keyword)
  • Numbers can be objects (if defined with the new keyword)
  • Strings can be objects (if defined with the new keyword)
  • Dates are always objects
  • Maths are always objects
  • Regular expressions are always objects
  • Arrays are always objects
  • Functions are always objects
  • Objects are always objects

All JavaScript values, except primitives, are objects.

JavaScript Primitives

A primitive value is a value that has no properties or methods.

3.14 is a primitive value

A primitive data type is data that has a primitive value.

JavaScript defines 7 types of primitive data types:

Examples

  • string
  • number
  • boolean
  • null
  • undefined
  • symbol
  • bigint

Immutable

Primitive values are immutable (they are hardcoded and cannot be changed).

if x = 3.14, you can change the value of x, but you cannot change the value of 3.14.

Value Type Comment
«Hello» string «Hello» is always «Hello»
3.14 number 3.14 is always 3.14
true boolean true is always true
false boolean false is always false
null null (object) null is always null
undefined undefined undefined is always undefined

Objects are Variables

JavaScript variables can contain single values:

Example

JavaScript variables can also contain many values.

Objects are variables too. But objects can contain many values.

Object values are written as name : value pairs (name and value separated by a colon).

Example

A JavaScript object is a collection of named values

It is a common practice to declare objects with the const keyword.

Example

Object Properties

The named values, in JavaScript objects, are called properties.

Property Value
firstName John
lastName Doe
age 50
eyeColor blue

Objects written as name value pairs are similar to:

  • Associative arrays in PHP
  • Dictionaries in Python
  • Hash tables in C
  • Hash maps in Java
  • Hashes in Ruby and Perl

Object Methods

Methods are actions that can be performed on objects.

Object properties can be both primitive values, other objects, and functions.

An object method is an object property containing a function definition.

Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function()

JavaScript objects are containers for named values, called properties and methods.

You will learn more about methods in the next chapters.

Creating a JavaScript Object

With JavaScript, you can define and create your own objects.

There are different ways to 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

This is the easiest way to create a JavaScript Object.

Using an object literal, you both define and create an object in one statement.

An object literal is a list of name:value pairs (like age:50) inside curly braces <>.

The following example creates a new JavaScript object with four properties:

Example

Spaces and line breaks are not important. An object definition can span multiple lines:

Example

This example creates an empty JavaScript object, and then adds 4 properties:

Example

const person = <>;
person.firstName = «John»;
person.lastName = «Doe»;
person.age = 50;
person.eyeColor = «blue»;

Using the JavaScript Keyword new

The following example create a new JavaScript object using new Object() , and then adds 4 properties:

Example

const person = new Object();
person.firstName = «John»;
person.lastName = «Doe»;
person.age = 50;
person.eyeColor = «blue»;

The examples above do exactly the same.

But there is no need to use new Object() .

For readability, simplicity and execution speed, use the object literal method.

JavaScript Objects are Mutable

Objects are mutable: They are addressed by reference, not by value.

If person is an object, the following statement will not create a copy of person:

The object x is not a copy of person. It is person. Both x and person are the same object.

Any changes to x will also change person, because x and person are the same object.

Example

const person = <
firstName:»John»,
lastName:»Doe»,
age:50, eyeColor:»blue»
>

const x = person;
x.age = 10; // Will change both x.age and person.age

Источник

Оцените статью