The keyword new determines whether or not a function is a constructor
it creates a new object, which is bound to this
the function is invoked with the value of this equal to the new object
it sets the new objects prototype to the prototype property of the constructor
it returns the object
function Users(fName, lName) {
this.firstname = fName;
this.lastName = lName;
};
var user1 = new Users("Luka","Tatarishvili");
Users.prototype.fullName = function() {
return this.fristName + " " + this.lastName;
};
var user2 = new Users("Luka","Tatarishvili");
note: it's prototype still has the full name method as a part of it even though we added it after creating object and of course the fullName works ass well on user2 that created after setting prototype
let newObj = {
total: 65,
increment: 1
}
const incrementTotal = function(obj, val){
obj.increment = val;
return function(){
console.log(obj.total);
obj.total = obj.total + obj.increment;
console.log(obj.total);
};
};
const incBy1 = incrementTotal(newObj, 1);
const incBy2 = incrementTotal(newObj, 2);
// will be incremented by 10
const incBy10 = incrementTotal(newObj, 10);
In this case, the result in each execution will be incremented by 10 because in the last line we have written 10 that will be regret 2 previous lines where we have written increment by 1 and increment by 2...
let theObj = {
total: 65,
increment: 1
}
// clone object
const cloneObj = function(obj){
return JSON.parse(JSON.stringify(obj));
};
const incrementTotal = function(obj, val){
let newObj = cloneObj(obj);
newObj.increment = val;
return function(){
console.log(newObj.total+" Before increment");
newObj.total = newObj.total + newObj.increment;
console.log(newObj.total+" After increment");
};
};
const incBy2 = incrementTotal(theObj, 2); // it will increment by 2
const incBy10 = incrementTotal(theObj, 10); // it will increment by 10
const incBy25 = incrementTotal(theObj, 25); // it will increment by 25
const incBy125 = incrementTotal(theObj, 25); // it will increment by 125
//and so on
We have cloned the object so every increment will be separated and they will increment as the value is passed. incBy2 will increment by 2, incby10 will increment by 10 and etc.