- Passing an object as reference
var functionName = function() {}
vsfunction functionName() {}
- event.target vs event.currentTarget
- event.stopPropagation vs event.preventDefault
- bind vs call vs apply
This medium article highlights shows 4 more ways of creating classes in JavaScript.
function SomeBaseClass(){
this.publicProperty='SomeValue';
}
SomeBaseClass.prototype = {
doThis : function(){},
doThat : function(){}
}
function MyClass(){
// this will allow the child class to inherit base class properties
SomeBaseClass.apply(this, arguments);
};
MyClass.prototype = Object.create(SomeBaseClass.prototype);
MyClass.prototype.constructor = MyClass;
var obj1 = new SomeBaseClass();
var obj2 = new MyClass();
console.log(obj1);
console.log(obj2);
This article covers refernces very nicely.
var person = {
name: 'Renars',
surname: 'Vilnis',
age: 22,
favorite_movies: [
'shrek',
'shrek_is_love',
'shrek_is_life',
],
siblings: {
mother: 'Eva',
father: 'Juris',
sister: 'Diana'
},
pets: undefined
};
// string reference test
var name = person.name;
name = 'Renārs';
console.log('Name:', person.name, name);
// Name: Renars Renārs
// INCORRECT
// number reference test
var age = person.age;
age = 23;
console.log('Age:', person.age, age);
// Age: 22 23
// INCORRECT
// array reference test
var movies = person.favorite_movies;
movies.push('Rambo');
console.log('Movies:', movies, person.favorite_movies);
// Movies: ["shrek", "shrek_is_love", "shrek_is_life", "Rambo"] ["shrek", "shrek_is_love", "shrek_is_life", "Rambo"]
// CORRECT
// object reference test
var siblings = person.siblings;
siblings.father = 'Juris Vilnis';
console.log('Siblings:', person.siblings, siblings);
// Siblings: Object {mother: "Eva", father: "Juris Vilnis", sister: "Diana"} Object {mother: "Eva", father: "Juris Vilnis", sister: "Diana"}
// CORRECT
// undefined variable reference
var pets = person.pets;
pets = {
Milady: {
type: 'cat',
age: 2
}
};
console.log('Pets:', person.pets, pets);
// Pets: undefined Object {Milady: Object}
// INCORRECT
For private variables just underscore them. As this example shows that with private variables aren't possible using this method.
var Person = (function() {
var name;
var Person2 = function(firstname, surname) {
name = firstname + ' ' + surname;
};
Person2.prototype.getName = function() {
return 'Name: ' + name;
};
return Person2;
})();
var person1 = new Person('John', 'Arrow');
var person2 = new Person('Smith', 'Colt');
console.log(person1.getName()); // Name: Smith Colt
console.log(person2.getName()); // Name: Smith Colt