Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Meet the JavaScript object

Monday, July 30th, 2012 by Servage

Hello PHP developer, please meet the JavaScript object. It’s your friend :-) Actually JavaScript has similar capabilities when it comes to object oriented programming, and mastering the JavaScript object is your first step on the way to program great code in JavaScript.

In the following example you will see a simple JavaScript object with the following features:

  • Constructor method
  • Defining an object property
  • Getter and setter functions for object property
  • How to instantiate and use the object

Example Object Code

var MyObject = function() {

  this.foo = 'bar';

  this.construct = function() {
    // Do you construction stuff here
  }

  this.setFoo(value) {
    this.foo = value;
  }

  this.getFoo() {
    return this.foo;
  }

  this.construct();
}

Example Object Usage

var test = new MyObject;
test.setFoo('New Value');
alert(test.getFoo());

Use console instead of alert

console.log(test.getFoo());

Using the console log method allows you to write variables into the concole, where you can easily debug them with your browser. This is a much more convenient debug workflow than using alerts.

Meet the JavaScript object, 4.8 out of 5 based on 4 ratings
Categories: Tips & Tricks

Keywords:

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.