0

why does this show me an error? the problem is with let p = 0; I just wanted to define the variable and then assign a value to int in the constructor. If i remove that let p = 0; it works but I don't understand it as I think this.p should refer to a pre-defined variable in the class, right? by the way, I don't know Javascript, my knowledge comes from Java

class Wizard {

   let p = 0;

  constructor(p) {
      this.p = p;
    // TODO replace this line.
  }
 power ()  {
     return this.p;
 }
}
let Gandalf = new Wizard(100);
farmcommand2
  • 1,418
  • 1
  • 13
  • 18
  • 1
    Might want to take a step back and learn some JS before trying to apply a completely different OOP paradigm to JS. Don't be confused into thinking JS has classes just because there's some syntactic sugar around JS prototypes, and don't think dynamic languages work the same way as static languages. – Dave Newton May 09 '17 at 19:35

1 Answers1

0

Well, JavaScript isn't an OOP language to begin with, or at the very least nearly not as strict as Java.

In this "soft OOP" you can dynamically assign attributes to an object without declaring it in the class. That's why it doesn't matter wether the attributes is declared.

Kuu Aku
  • 320
  • 2
  • 6
  • Nonsense; it's OOP. You're confusing typing semantics with OOP-in-general. Using a different approach doesn't make it non-OOP. – Dave Newton May 09 '17 at 19:43
  • Re-Reading myself, I see that what I said might be unclear. What I meant is that js do not follow all the principles of OOP. Encapsulation for example, isn't really strictly applied as you can not only access an object attributes directly as a default, but also dynamically change an object attributes list without changing the class it is an instance of. The different approach is for me the prototypes-based data structures. I'm indeed kind of wrong when I say that js isn't OOP. However, this is not the OOP the author is used at with Java, hence the"soft-OOP" – Kuu Aku May 09 '17 at 21:03
  • The problem with applying all rules of OOP to all OOP languages is that it doesn't work. "Encapsulation" doesn't imply inaccessibility, e.g., I don't think too many people would say Ruby isn't OOP, but you have access to essentially anything. Even in Java you can play games with reflection. E.g., https://en.wikipedia.org/wiki/Object-oriented_programming#Encapsulation more or less sums this up. I'm uncomfortable saying things like "soft-"/"hard-"OOP when the issues are around typing and data access, which is a different thing. – Dave Newton May 09 '17 at 21:07