Alexe Bogdan
Web Developer, JavaScript Lover, User Experience Professional, working in the web and mobile application development industry.
var animal = {
isDog: true,
name: 'Sparky',
bark: function(){
return 'Bark!'
}
}
var array = [1,2,3];
>> array.length //3
array.push(4);
>> array.length //4
//Function Declaration
function fn(x){
return x;
}
//Function Expression
var fn = function(){
return x;
}
var Person = function(name){
this.name = name;
this.sayName = function(){
return 'My name is ' + this.name;
};
};
//Create new instance
var john = new Person('John');
>> john.sayName(); //John
>> john instanceof Person //true
>> john instanceof Object //true
var Person = function(name){
this.name = name;
this.sayName = function(){
return 'My name is ' + this.name;
};
};
//Create new instance
var james= new Person('James');
//Augment the prototype object
Person.prototype.changeName = function (newName) {
this.name = newName;
};
james.changeName('Joe');
>>james.sayName(); //Joe
var Person = function(name){
this.name = name;
};
Person.prototype.changeName = function (newName) {
this.name = newName;
};
Person.prototype.sayName = function(){
return 'My name is ' + this.name;
};
var james= new Person('James');
>> james.hasOwnProperty('changeName'); //false
>> james.__proto__.hasOwnProperty('changeName'); //true
var Dad = function(kids){ this.kids = kids || 0; }; Dad.prototype = new Person(); Dad.prototype.constructor = Dad; var dad = new Dad(2); //{kids:2, name:undefined, changeName:function, sayName:function} >>dad instanceof Dad; //true
>>dad instanceof Person; //true
>>dad instanceof Object; //true
if(true){
var inside = 1;
}
>>inside //1
function fn(){
var private = true;
//private it's available here
}
>>private //undefined
(function(){
var a = 1;
var b = 2;
alert(a + b);
})();
(function(win){
var a = 1, b = 2,
//Closure
sum = function(){
return a + b;
}
win.sum = sum;
})(window);
>> sum()//3
//bad
for (var i = 0; i < 5; i++) {
window.setTimeout(function(){
alert(i); // will alert 5 every time
}, 200);
}
//good
for (var i = 0; i < 5; i++) {
(function(index) {
window.setTimeout(function() { alert(index); }, 100);
})(i);
}
By Alexe Bogdan
Web Developer, JavaScript Lover, User Experience Professional, working in the web and mobile application development industry.