This tutorial boilerplate shows you how to create JS objects, manipulate them, write and use functions within them and call external material using Ajax requests.
//This tutorial is aimed at showing you how to create an use objects in every day code. You *could*
//create an object as a Library for all your projects, or for one simple task that you replicate in
//a number of places. This makes things faster and easier. AngularJS is built on this 'basic' principle.
//Make sure you have the JQuery 2.2.0 library selected.
//This is a JS Object, which can also be reffered to as a Library
//In this example, the object is created using JSON
//Setup the variables first - can be the result of some input / Ajax call
arg1 = 'some value';
arg2 = 'some other value';
var MAJTools = { //Notice we start a new object with the curly braces
'a1' : arg1, //because this is a JSON object, we need to use the : to assign property names and values
'a2' : arg2, //and a comma between the items, not a semi-colon
};
console.log(MAJTools);
//A new object can also be called using new Object:
var MAJTools2 = new someObject(1,2); //See, we can pass objects easily.
function someObject(parameter1, parameter2) { //In this way, we can pass variables to the new object
this.p1 = parameter1; //We used - this - to allocate the variable to the object
this.p2 = parameter2;
}
console.log(MAJTools2);
//Update an object parameter
MAJTools2.p1 = 484; //see how we use dot notation to access the property?
console.log(MAJTools2);
MAJTools2.p4 = 4849; //This works, but we didn't set it when we created the object. Can you think of why?
console.log(MAJTools2);
////Object functions
//So, you want to store a function in an object. This is a good idea when you want to condense your code and make it more readable.
//Check this out.
MAJTools.returnPropertiesFunction = function() {
var myReturnArray = [this.a1, this.a2];
return myReturnArray;
}
console.log(MAJTools.returnPropertiesFunction()); //This will return to me an array
//Let's say we have a couple of methods that don't return anything, but they do some grunt work. We can chain these methods together....
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.