JavaScript:
1. Use ’this’ e.g. when you want to create new objects based on your function (remember to use ’new’ when creating new objects + the convention is to use capital letters for the name of the function in such cases to show they are classes; classes behave like blueprints, prototypes, etc.: they are there in order to enable you with the help of ’new’ to make as many instances of them as you want):
function Car(name){
this.name = name;
this.sayMyName = function() {
console.log(”This car’s name is ” + this.name);
};
}
var kitt = new Car(”Knight Industries Two Thousand”);
var modelS = new Car(”Tesla Model S SuperCar”);
kitt.sayMyName(); // => My name is Knight Industries Two Thousand
modelS.sayMyName(); // => My name is Tesla Model S SuperCar
2. When invoking a method in an object, ’this’ becomes the object itself:
var kitt = {
name: ’Knight Industries Two Thousand’,
sayMyName: function() {
console.log(”My name is ” + this.name);
}
};
var modelS = {
name: ’Tesla Model S SuperCar’,
sayMyName: function() {
console.log(”My name is ” + this.name);
}
};
kitt.sayMyName();
modelS.sayMyName();
3. Simple multiplying function with ’this’:
function Calculator () {
this.total = 0;
this.multiply = function(first, second) {
this.total = first * second;
console.log(this.total);
};
}
var s = new Calculator();
s.multiply(2,3);
4. Calculator with prototype:
function Calculator(){
this.number1 = 0;
this.number2 = 0;
this.result = 0;
Calculator.prototype.askNumber1 = function(){
this.number1 = parseInt(prompt())
}
Calculator.prototype.askNumber2 = function(){
this.number2 = parseInt(prompt())
}
Calculator.prototype.showResult = function(){
console.log(this.result)
}
Calculator.prototype.add = function(){
this.result = this.number1 + this.number2
}
Calculator.prototype.multiply = function(){
this.result = this.number1 * this.number2
}
Calculator.prototype.substract = function(){
this.result = this.number1 – this.number2
}
Calculator.prototype.divide = function(){
this.result = this.number1 / this.number2
}
}
Calculator.prototype.add = function() {
this.result
}
var calc = new Calculator()
calc.askNumber1();
calc.askNumber2();
calc.add();
calc.showResult();
5. Link to DOM (Document Object Model) properties: https://developer.mozilla.org/en-US/docs/Web/API/Document#Properties
6. Link to DOM methods: https://developer.mozilla.org/en-US/docs/Web/API/Document#Methods