+ 1
I really don't get object methods. Can somebody explain it to me?
I don't get the use and how to make it.
2 Respostas
+ 5
Can you imagine a car?
The car is an object
var car = {};
This car is red, that's object property
car.color = red;
And this red car has some functions like print its color
car.print_color = function(){
console.log(car.color);
}
When we call car.print_color(); it will print car color. Okay let's make function for change color
car.set_color = function(color){
car.color = color;
}
When we call car.set_color('blue'); car's color will be blue.
In object functions we can use this keyword instead of object variable like this:
car.set_color = function(color){
this.color = color;
}
In this is now 'stored' car, but only in function.
How can you use this? OOP programming is about make code more synoptical. In structured programming you can write functions which do same work but... Let's imagine you are working on JavaScript game for example and you will have 100 cars. It is really nicer and better to have all this cars in array of objects from common class. You can easier create and manipulate with cars or other objects. And when you look at OOP code and structured code, you will see really big difference. I think so. Object and classes are usefull in small block of code, but in complex projects is very hard to work without them. All examples which present OOP are very simply, so you may don't get the use. But trust me... In bigger sruffs you will need these functions.
+ 1
Thanks! This is helpful!