Using Object from Javascript

If you want to create an object and use therm from javascript. Here is some solution:

1. Extend javascript Object:

// Object
var myObject = new Object();
// Properties:
myObject.var1 = true;
myObject.var2 = null;
// Method:
myObject.method1 = function() {
};
myObject.method2 = function(abc) {
};

I've change JSON object to Object Literal object. Thanks @hoatle for correct me

2. Use JSONObject Literal object:

// Object
var myObject = {
  // Properties
  var1: true,
  var2: null,
  // Method
  method1: function() {
  },
  method2: function(abc) {
  }
};

3. Use function constructor:

// Class
var myClass = function() {
  // Properties
  this.var1 = true;
  this.var2 = null;
};
// Method
myClass.prototype.method1 = function() {
};
myClass.prototype.method2 = function(abc) {
};
// Create object from class
var myObject = new myClass();

Example:

Extend javascript Object

var helloWorld1 = new Object();
helloWorld1.text = 'Hello world from extend javascript Object';
helloWorld1.say = function() {
  alert(this.text);
};

Use JSONObject Literal object

var helloWorld2 = {
  text: 'Hello world from json object',
  say: function() {
    alert(this.text);
  }
};

Use constructor function with no param

var helloWorld3Class = function() {
  this.text = 'Hello world from class with no param';
};
helloWorld3Class.prototype.say = function() {
  alert(this.text);
};
var helloWorld3 = new helloWorld3Class();

Use constructor function with param

var helloWorld4Class = function(string) {
  this.text = string;
};
helloWorld4Class.prototype.say = function() {
  alert(this.text);
};
var helloWorld4 = new helloWorld4Class('Hello world from constructor with param');

Some other use with constructor

var helloWorld5Class = function() {
  this.text = 'Hello world from contructor function';
  this.say = function() {
    alert(this.text);
  };
};
var helloWorld5 = new helloWorld5Class();

Categogy: 

Add new comment