Objects and classes

In Java, you create a class to represent a concept, for example, a User class. The User class has a constructor, some fields, and methods. And you use its constructor to instantiate a User object. And every object in Java is an instance of the associated class that provides code sharing among its instances. You can extend the User class to create, for example, a TeamMember class.

In JavaScript, there are several ways to create an object:

  • The Object() constructor method
  • The object literal method
  • The constructor function method
  • The Object.create() method
  • The creator function method
  • The ES6 class method

Let's look at each method one at a time.

The Object constructor method looks like this:

// Call the Object constructor with new
var user = new Object();
user.name = 'Sunny';
user.interests = ['Traveling', 'Swimming'];
user.greeting = function () {
console.log('Hi, I'm ' + this.name + '.');
};
user.greeting(); // Hi, I'm Sunny.

The Object constructor creates an object wrapper. This is not a recommended approach, even though it is valid in JavaScript. In practice, it is better to use an object literal instead, which makes the code compact.

The object literal method looks like this:

// Create a user with object literal
var user = {
name: 'Sunny',
interests: ['Traveling', 'Swimming'],
greeting: function () {
console.log('Hi, I'm ' + this.name + '.');
}
}
user.greeting(); // Hi, I'm Sunny.

The object literal is a compact syntax to create an object in JavaScript and it is the recommended way of creating an object over new Object(). Starting from ES5, object literals also support getter and setter accessors, as can be seen here:

var user = {
get role() {
return 'Engineer';
}
}
user.role; // Engineer

And if you try to assign a value to role, it will stay unchanged because there is no setter accessor defined for the role property.

The constructor function method looks like this:

// Create a constructor function
function User (name, interests) {
this.name = name;
this.interests = interests;
this.greeting = function () {
console.log('Hi, I'm ' + this.name + '.');
}
}
// Call the constructor with new to create a user object
var user = new User('Sunny', ['Traveling', 'Swimming']);
user.greeting(); // Hi, I'm Sunny.

This syntax is very close to the one in Java. JavaScript is very tolerant, and you can omit the parenthesis when calling the constructor. However, this will not pass any arguments to the constructor, as can be seen here:

var user = new User;
console.log(user.name); // undefined

And again, even though this is valid in JavaScript, it is not recommended to omit the parenthesis.

The Object.create() method looks like this:

// Use Object.create() method with the prototype of
// User constructor function created above
var user = Object.create(User.prototype, {
name: { value: 'Sunny' },
interests: { value: ['Traveling', 'Swimming']}
});
user.greeting(); // Uncaught TypeError: user.greeting() is not a //function

The reason greeting() is not a function of the user object here is that the Object.create() method creates a new object with the constructor's prototype object. And the greeting function is not defined in User.prototype, or passed in the second argument of Object.create(). To make the user be able to greet, we can either pass the greeting function in the second argument, or we can add it to the User constructor's prototype object. The difference is that the first approach only adds the greeting function to the current user object. If you created another user without passing in the greeting function, that user won't have greeting function. On the other hand, adding the function to the prototype object will add the greeting function to all the objects created by that constructor. Let's add it to the User prototype object:

// Add greeting to prototype object
User.prototype.greeting = function () {
console.log('Hi, I'm ' + this.name + '.');
}
user.greeting(); // Hi, I'm Sunny.

Actually, using a prototype is how a superclass provides methods for subclasses to inherit in JavaScript. We will talk about that in detail later.

The creator function method looks like this:

// Use a creator function with an object as its return value
function createUser (name, interests) {
var user = {};
user.name = name;
user.interests = interests;
user.greeting = function () {
console.log('Hi, I'm ' + this.name + '.');
};
return user;
}
// Call the creator function with parameters
var user = createUser('Sunny', ['Traveling', 'Swimming']);
user.greeting(); // Hi, I'm Sunny.

The creator function here is a factory method, similar to the static factory method that used to instantiate an object in Java. And it is merely a pattern because underneath it wraps the object creation details inside of the creator function.

The ES6 class method looks like this:

// Create User class
class User {
// Equivalent to User constructor function
constructor (name, interests) {
this.name = name;
this.interests = interests;
}
// Equivalent to User.prototype.greeting
greeting () {
console.log('Hi, I'm ' + this.name + '.')
}
}
let user = new User('Sunny', ['Traveling', 'Swimming']);
user.greeting(); // Hi, I'm Sunny.

This is very close to the syntax in Java. Instead of using the class declaration, you can also use the class expression to create the class, as follows:

// Use class expression
let User = class {
constructor (name, interests) {
this.name = name;
this.interests = interests;
}
greeting () {
console.log('Hi, I'm ' + this.name + '.')
}
}

Even though it uses the same keyword, class, class in JavaScript is quite different from the class in Java. For example, there is no static class and no private class in JavaScript. We will talk more about class in the ES6 section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.27.178