Adding Methods to Objects

By: Dusty Arlia
Published on Wednesday, June 12, 2013, 10:51 AM
Last Updated on Friday, July 03, 2015 at 3:52 PM
Total Updates: 6

When you are first creating your object using object literal notation, you can add your methods (accessor properties) in the object literal. Here is an example of an object literal:

var math_problem {
	a: 1,
	b: 2,
	get c() {return (this.a +this.b);},
	set c(number_param) {
		var old = (this.a +this.b);
		var ratio = number_param/old;
		this.a *= ratio;
		this.b *= ratio;

When methods are added using the object literal notation, you will see that the method name will come after the word get or set (or both if the method acts as both a getter and setter). Methods are properties (accessor properties) of objects. If a property is both a getter and a setter, it is a read/write property.

If your object already exists and you want to add a method, use dot-syntax like this:

//object declaration and initialization
var employee = {
    "first_name": "Justin",
    "last_name": "Bieber"

//attaching the greetEmployee() 
//method to the employee object
employee.greetEmployee = funtion(first_name) {
    var greeting = "Hello " + first_name + "!";
    return greeting;

Since methods are a type of property (accessor property), you can also add methods to objects using the defineProperty() method. Pass the object you would like the function attached to, the name of the property to be created (function name), and the property descriptor object (holds the four attribute values). Here is the basic syntax:

Object.defineProperty(your_object, "ex_function_name", {get:  function()  {return function_result;}});
your_object.ex_function_name  //returns the value of the function_result