0

I'm a beginner and following a long from a udemy course and I've come across this example where we use the THIS keyword to reference the properties within it's object. However, I don't understand why we can't just grab the property like we would normally do when we are outside of the object by doing: objectname.property. I tested it and it seems to work fine. I'm obviously missing something so if someone could let me know that would be hugely appreciated! The example is below. Instead of using this, why not just use mark.bmi for instance.

const mark = {
    name: `mark`,
    mass: 92,
    height: 1.95,
    bmiCalc: function() {
       this.bmi = this.mass / (this.height * this.height);
       return this.bmi;
    }
}
4xgold
  • 1
  • This will give you proper insight : https://javascript.info/object-methods – Harmandeep Singh Kalsi Jun 14 '20 at 08:14
  • `mark2 = Object.create(mark), mark2.mass=0, console.log(mark.bmiCalc(), mark2.bmiCalc())` – user120242 Jun 14 '20 at 08:17
  • Basically an object is an the class becoming alive. The Class is the abstraction of concepts and data with ways to access them, if the class has to reference itself via a given name defined outside it would defeat the purpose of encapsulation and abstraction. As the answer by @jlsuarez, the function would break if the variable name 'mark' changed. Also you may created dynamic object without a name of a reference to be called. The object should be something that isn't dependent of 'outside'. Even when it needs something from outside, that something has to be passed to it not called from within – Mohammed Joraid Jun 14 '20 at 08:41

2 Answers2

0

Properties can be added dynamically to an object. You presented a trivial case, but in most of the cases, the compiler would not be able to decide without a "this." if you reference a member of the current object, or some global variable

Iter Ator
  • 5,817
  • 13
  • 53
  • 116
0

Change the variable name mark to jacob, you don't need to refactor. But if you had changed this to mark then you needed to change it also to the new variable name.

Usually you create more objects (or instances) from a class. The method defined in the class applies to more than just this object (mark). That's the reason for using this in object oriented programming.

D. Schreier
  • 1,462
  • 1
  • 17
  • 29
jlsuarez
  • 9
  • 3
  • I tend to agree with your idea. Basically an object is an the class becoming alive. The Class is the abstraction of concepts and data with ways to access them, if the class has to reference itself via a given name that was declared outside it, that would defeat the purpose of encapsulation and abstraction. – Mohammed Joraid Jun 14 '20 at 08:43