In javascript
there are no classes. That being said you can simulate classes using few different ways.
Using a function and defining methods to its prototype
var Person = function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
};
// you can define Person.fullname = function() {} straight to the function
// drawback to this is fullname function will be created everytimg you create a new Person
// instead you can create fullname in the prototype of the Person so it only gets created once
Person.prototype.fullname = function() {
return this.firstName + ' ' + this.lastName;
};
var person = new Person('John', 'Doe');
person.fullname(); // John Doe
Using object literals
var Person = {
firstName: 'John',
lastName: 'Doe',
fullname: function() {
return this.firstName + ' ' + this.lastName;
}
};
Person.fullname(); // John Doe
Person.firstName = 'Jane';
Person.fullname(); // Jane Doe
Using Singleton
var person = new function() {
this.firstName = 'John';
this.lastName = 'Doe';
this.fullname = function() {
return this.firstName + ' ' + this.lastName;
};
};
person.fullname(); // John Doe
person.firstName = 'Jane';
person.fullname(); // Jane Doe
If you are planning to get more closer to how java
classes work, apply inheritance, etc then I suggest you to go with the first method. Below is example of a simple inheritance using prototype
.
var Person = function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
};
Person.prototype.fullname = function() {
return this.firstName + ' ' + this.lastName;
};
Person.prototype.getFirstName = function() {
return this.firstName;
};
Person.prototype.getLastName = function() {
return this.lastName;
};
Person.prototype.setLastName = function(lastName) {
return this.lastName = lastName;
};
Person.prototype.setFirstName = function(firstName) {
return this.firstName = firstName;
};
var Student = function(firstName, lastName, grade) {
this.grade = grade;
Person.call(this, firstName, lastName);
};
Student.prototype = Object.create(Person.prototype);
Student.prototype.getGrade = function() {
return this.grade;
};
var student = new Student('John', 'Doe', '5th');
student.fullname(); // John Doe
student.getFirstName(); // John
student.setFirstName('Jane');
student.getFirstName(); // Jane
student.getGrade(); // 5th
That should explain how you can use classes in javascript
similar to you are used to in java
.
What is difference between using dot notation
and brackets
to access object properties?
Long answer short, both behave exactly the same. But there would be instances where dot notation
will not always work. For example:
var person = {
"first name": "john",
"last name": "doe",
"fullname": "john doe"
};
person.fullname; // john doe
// to access first name property of person
person.first name; // will not work
person["first name"]; // john