Categories
JavaScript Tutorials

Altering Properties/Methods

JavaScript is a dynamic language; it allows you to alter properties and methods of existing objects at any time. This includes adding new properties or deleting them. You can start with a blank object and add properties later. Let’s see how you can go about doing this.

An empty object:

var hero = {};

Accessing a non-existing property:

typeof hero.breed
//"undefined"

Adding some properties and a method:

hero.breed = 'turtle';
hero.name = 'Leonardo';
hero.sayName = function() {return hero.name;};

Calling the method:

hero.sayName();
//Leonardo

Deleting a property:

delete hero.name;
//true

Calling the method again will no longer work:

hero.sayName();
//reference to undefined property hero.name

Using this value

In the previous example, the method sayName() used hero.name to access the name property of the hero object. When you’re inside a method though, there is another way to access the object this method belongs to:

By using the special value ‘this’:

var hero = {
  name: 'Rafaelo',
  sayName: function() {
    return this.name;
  }
};
hero.sayName();
//"Rafaelo"

So when you say ‘this’, you are actually saying “this object” or “the current object”.

Examples

Create an empty object and add a property to it.
var obj = { };
obj.message = 'Hello';
Create an object with firstname and lastname properties and add a method to print the full name in console.
var person = {
  firstname: 'Bob',
  lastname: 'Smith'
};
person.getFullName = function() {
  console.log(person.firstname + ' ' + person.lastname);
}
Create an object with firstname and lastname properties and add a method to print the full name in console using the ‘this’ keyword.
var person = {
  firstname: 'Bob',
  lastname: 'Smith'
};
person.getFullName = function() {
  console.log(this.firstname + ' ' + this.lastname);
}
Create an object with firstname and lastname properties and add a method which can change the firstname using the ‘this’ keyword.
var person = {
  firstname: 'Bob',
  lastname: 'Smith'
};
person.changeFirstname = function() {
  this.firstname = 'Will';
}