Created by
The typical use case of OOP is in big software systems on which works multiple developers.
Java | JavaScript |
---|---|
Classes | Functions |
Constructors | Functions |
Methods | Functions |
Tables excerpt from Douglas Crockford's "Classical Inheritance in JavaScript"
{}
.
var obj = {
property1: value1,
property2: value2,
...
propertyN: valueN
};
By object literals in JavaScript, we can create associative arrays/dictionaries data structures.
var apple = {
color: "red",
price: [23.5, 22, 25],
calcMinPrice: function(){
return Math.min( ...this.price ); // from ES6
},
calcMaxPrice: function(){
return Math.max( ...this.price ); // from ES6
}
}
console.log( "apple object", apple );
console.log( "apple min price", apple.calcMinPrice() );
"Factory" - a function which creates object instances!
let carFactory = function(model, year){
var obj = {};
obj.model = model;
obj.year = year;
return obj;
}
// create new car object:
let car1 = carFactory('FORD Mustang', 1998);
var objFactory = function(name){
var obj = {};
obj.name = name;
obj.sayName = function(){
console.log(`I'm object: ${obj.name}`)
};
return obj;
}
var obj1 = objFactory('Object 1');
var obj2 = objFactory('Object 2');
obj1.sayName();
obj2.sayName();
// I'm object: Object 1
// I'm object: Object 2
"use strict";
let objFactory = function(name){
// "private members"
let _name = name;
let obj = {
// public members:
sayName: function(){
console.log(`I'm object: ${_name}`)
}
};
return obj;
}
let obj1 = objFactory('Object 1');
obj1.sayName();
// but obj1 name can not be accessed directly:
console.log(`obj1.name: ${obj1.name}`);
// *** OUTPUT ***
// I'm object: Object 1
// obj1.name: undefined
Implement the devFactory
factory function, which creates objects:
// properties
name: string,
salary: number,
// methods
getSalary()
returns salary
increaseSalary(incrValue, pass)
increments salary with incrValue, if pass == 'abracadabra'
"use strict";
let devFactory = function(name, salary){
// YOUR CODE HERE
}
let dev1 = devFactory('Peter', 1000);
let dev2 = devFactory('Maria', 1200);
console.log(`${dev1.name} salary is ${dev1.getSalary()}`);
console.log(`${dev2.name} salary is ${dev2.getSalary()}`);
dev1.increaseSalary(500, 'abracadabra');
dev2.increaseSalary(100, '123');
console.log(`${dev1.name} salary after promotion is ${dev1.getSalary()}`);
console.log(`${dev2.name} salary after promotion is ${dev2.getSalary()}`);
// *** OUTPUT ***
// Peter salary is 1000
// Maria salary is 1200
// Wrong password! Maria salary will not be increased!
// Peter salary after promotion is 1500
// Maria salary after promotion is 1200
Object.create()
// the Constructor Function:
let AppleConstructor = function( color, prices ){
console.log("AppleConstructor is called!");
this.color = color;
this.prices = prices;
this.calcMinPrice = function(){
return Math.min( ...this.prices ); // from ES6
};
this.calcMaxPrice = function(){
return Math.max( ...this.prices ); // from ES6
};
}
// objects constructing:
let apple1 = new AppleConstructor("red", [3.5, 2.05, 2.5]);
let appleN = new AppleConstructor("green", [1.80, 2.10, 2.40]);
// objects usage:
console.log( "apple1 min price: ", apple1.calcMinPrice());
new
and this
problems!
"use strict";
// constructors:
function AudioPlayer(name){
this.name = name;
this.play = function(){
console.log(`${this.name} is playing as Audio!`);
}
}
function VideoPlayer(name){
this.name = name;
this.play = function(){
console.log(`${this.name} is playing as Video!`);
}
}
// the factory - explicitly returns an object:
function mediaPlayerMaker(name) {
// if filename ends in 'mp3' or 'ogg' or 'flack' => return AudioPlayer object
if(name.match(/\.(?:mp3|ogg|flack)$/i) ){
return new AudioPlayer(name);
}
// if filename ends in 'mp4' or 'avi' or 'divx' => return VideoPlayer object
if (name.match(/\.(?:mp4|avi|divx)$/i)) {
return new VideoPlayer(name);
}
}
// the instancies
const player1 = mediaPlayerMaker('time_lapse.mp3');
const player2 = mediaPlayerMaker('micahel_nyman_band_live.avi');
// the usage
player1.play();
player2.play();
// time_lapse.mp3 is playing as Audio!
// micahel_nyman_band_live.avi is playing as Video!
get = object.property;
object.property = set;
property
name must be a valid identifier!
let obj = {};
obj.name = 'Ada'; // valid
obj._id = 1; // valid
obj.$1 = "first"; // valid
obj.1 = "first"; // invalid
get = object[property_name];
object[property_name] = set;
property_name
is a string, or expression that evaluates to string!property_name
can be any string, not necessarily valid identifier.
let obj = {};
let keyName = 2;
obj["1"] = "first"; // valid
obj[keyName] = "second"; // valid
console.log(obj)
// Object {1: "first", 2: "second"}
let obj={
prop1: 1,
prop2: 2,
prop1: 3,
prop4: 4
}
console.log(obj);
// Object {prop1: 3, prop2: 2, prop4: 4}
let i = 0;
let obj = {
[`key${++i}`] : i,
[`key${++i}`] : i,
[`key${++i}`] : i,
};
console.dir(obj);
// Object
// key1: 1
// key2: 2
// key3: 3
let name = 'Ada', age = 21;
let user = {name, age};
console.log(user);
// { name: 'Ada', age: 21 }
var obj = {
id: 1,
sayID(){
console.log(this.id)
},
}
obj.sayID();
// 1
let user = {
'name':'Ada',
'age': 21,
'address':{
'town': 'Varna',
'zip': 1234
}
}
for (const key in user) {
console.log(key);
}
// name
// age
// address
for..in
statement with for...of statement which is used to iterate over arrays, strings and other iterable objectsObject.keys()
let user = {
'name':'Ada',
'age': 21,
'address':{
'town': 'Varna',
'zip': 1234
}
}
const keys = Object.keys(user)
console.log(keys);
// [ 'name', 'age', 'address' ]
Object.values()
let user = {
'name':'Ada',
'age': 21,
'address':{
'town': 'Varna',
'zip': 1234
}
}
const keys = Object.values(user)
// [ 'Ada', 21, { town: 'Varna', zip: 1234 } ]
These slides are based on
customised version of
framework