Stanislav Zorjan - Stasha - Full Stack Software Engineer and Game Development Hobbyist - Prague


JavaScript OOP - Classes & Objects
JavaScript OOP - Methods & Properties
JavaScript OOP - Getters & Setters
JavaScript OOP - Encapsulation
JavaScript OOP - Inheritance

 

JavaScript OOP - Methods and Properties

 

// Dynamically adding methods and properties.
// Because all objects in javascript are dynamic we can "inject" methods 
// and properties.
// All "injected" methods and properties are public.
// Methods and properties can be injected in different ways through 
// a "Class.prototype", "Instance.constructor.prototype" or just attaching 
// them to instance like "instance.someProperty, instance.someMethod".
// First and second way have same results. They "inject" methods and 
// properties at the class level. It means all instances will have those 
// methods and properties no matter if they already exist or not.
// The third way adds methods and properties only to that instance.

// Empty class
function SomeClass(){ }

// Creating objects;
var sc = new SomeClass();
var sc2 = new SomeClass();
var img = new Image();

// Injecting methods and properties at the class level
// Injecting "name" property to "SameClass" with initial value "Stasha"
SomeClass.prototype.name = "Stasha";
// Injecting "method0" to "SomeClass" 
sc.constructor.prototype.method0 = function(){return "Method 0"};
// Injecting "method0" method to "SameClass"
Image.prototype.method0 = function(){return "Image Method 0"};

// Injecting methods and properties to instances
sc.lastName = "Zorjan"
sc.method1 = function(){return "SC Methodf 1"};
sc2.method1 = function(){return "SC2 Method 1"};
img.method1 = function(){return "Image Method 1"};

alert(sc.name+","+sc.lastName+ ", "+sc2.name+", "+sc.method0()+", "
+sc2.method0()+", "+img.method0()+", "+sc.method1()+", "+sc2.method1()+", "
+img.method1())




Comments (0)