Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

same method or variable name in a javascript class behaves differently

class Parent{
    method(){
        console.log("Parent");
    }
}
class Child extends Parent{
    method(){
        console.log("Parent");
    }
}
var child = new Child();
console.log(child.method);

console return method in child class which is a expected behaviour.

class Parent{
    method = "sss"
}
class Child extends Parent{
    method(){
        console.log("Child")
    }
}
var child = new Child();
console.log(child.method)

why does the console return method variable - "sss" in Parent class ?

like image 784
MOHAMED SIKKANDAR AFZAL M Avatar asked Oct 20 '25 03:10

MOHAMED SIKKANDAR AFZAL M


1 Answers

class Parent {
    method = "sss";
}

Is essentially a shortcut for:

class Parent {
    constructor() {
        this.method = "sss";
    }
}

Meaning that there are some important differences with:

class Parent {
    method() {
        console.log("Parent");
    }
}
  1. In the method = "sss" variant, method will be set as an own property of the created instance (new Child()).

    child.hasOwnProperty("method") //=> true
    

    Whereas defining a normal method method() { console.log("Parent") } will not be set as an own property of the instance. Instead it is set on the prototype chain.

    Parent.prototype.hasOwnProperty("method") //=> true
    
  2. The constructor code only runs whenever you initialize an instance. Meaning that this.method = "sss" will always run after you've defined the Parent and Child classes (whenever you create the instance with new).

class Parent {
    prop = "parent value";
    // aka
    // constructor() {
    //   this.prop = "parent value";
    // }
    method() {
        console.log("Parent");
    }
}

class Child extends Parent {
    prop() {
      return "child Value";
    }
    method() {
        console.log("Child");
    }
}

const child = new Child();

const log = (jsString) => console.log(jsString, '//=>', eval(jsString));
log(`child.hasOwnProperty("prop")`);
log(`child.hasOwnProperty("method")`);
log(`Parent.prototype.hasOwnProperty("prop")`);
log(`Parent.prototype.hasOwnProperty("method")`);

The final Child instance structure looks like this:

new Child()
// returns
Child{ // Child instance depicted using object notation
  // own properties
  prop: "parent value", // set by the Parent constructor

  // prototype chain depicted using the __proto__ (deprecated) property
  __proto__: {
    // Child.prototype
    prop() { return "child Value" },
    method() { console.log("Child") },

    __proto__: {
      // Parent.prototype
      method() { console.log("Parent") },
    }
  }
}

For more detailed info I suggest reading through the MDN Public class fields page.

like image 98
3limin4t0r Avatar answered Oct 22 '25 18:10

3limin4t0r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!