var f = function(arg) {
if (arg != null) {
document.write(arg);
document.write("<br/>");
} else if (arg == undefined) {
document.write("undefined<br/>");
}
else {
document.write("<br/>");
}
};
// classes
// as convention use Person instead of person to denote a class. This function returns an object which has name, age and created properties.
function Person(name, age){
//public
this.name = name;
this.age = age;
this.created = new Date();
this.dowork = function(arg){f(arg);};
//private member is declared by using the var keyword
var _pvtMember = "something private";
//properties
Object.defineProperty(this, "propMember", {
get: function() {return _pvtMember;},
set: function(value) {_pvtMember = value;}
});
//defining a static member
Person.staticMember = "static Member";
Person.staticFunc = function(){f(this.name);};
//Prototype object - every js 'type' is associated with a prototype object. the prototype is just an object to which properties can be added. all instances of a 'type' can share the properties or functions of prototype. In case of static, instances can not access the static properties or functions.
//sharing data amongst instances
Person.prototype.sharedProp = "shared prop";
//sharing functions amongst instances
Person.prototype.sharedFunc = function(){f(this.name);};
};
var personInst = new Person("Roger Federer", 32);
f(personInst.name + " " + personInst.age + " " + personInst.created);
f(personInst._pvtMember); //unable to access this as its private
f(personInst.propMember); //able to access this property
personInst.propMember = "something else"; //using the setter property
f(personInst.propMember);
f(personInst.staticMember);//person instance cant access because its static
f(Person.staticMember);//works because its accessed via the class Person instead of instance...
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.