How to add an method to a class in Javascript ES6
Asked Answered
A

4

25

I need do add a method to a Javascript class using the new syntax. I tried this way:

class X{

    constructor() {
        this.a = 'b'
    }

    x(){

    }
}

X.prototype.y = function (){
    console.log('y')
}

var x = new X()

x.y()

console.log(X) // print the  the class but not the new method.

It just prints:

class X{

    constructor() {
        this.a = 'b'
    }

    x(){}
}

But I expected

class X{

        constructor() {
            this.a = 'b'
        }

        x(){}

        y(){
            console.log('y');
        }
    }

How could I add a new method to a Javascript class?

Alcohol answered 5/3, 2016 at 12:1 Comment(4)
just for sake of knowledge: I heard that javascript is classless. What does it means?Extravagance
I expected the new method showed in the log, inside the class. Console.log(X) should log the class code.Alcohol
You added method to the prototype, not as own property. Read about difference.Succumb
How could I add the method as a property using EcmaScript 6 sugar syntax? Note that I need to add a method after class declaration given the fact I will receive method name and parameter names as strings.Alcohol
M
13

this works fine, if you are checking this in google chrome console, then please check by expanding proto node. or alternatively try checking console.log(X.y) or console.log(X.prototype.y) or console.log(x.y) this must print that function

Manor answered 5/3, 2016 at 12:15 Comment(1)
I need y acting like x. For example, when I log X it must print Both x and y inside X.Alcohol
F
7

There are two major ways to add methods to a class, this can be within the scope of the class when writing the code or using ".prototype" to attach a method to your class. Below is an example of adding a method within the class scope:

class Person {
   constructor(fName, lName) {
      this.firstName = fName;
      this.lastName = lName;
   }
   sayName = function() {
   return `My Name is ${this.firstName} ${this.lastName}`
   }
}
const firstPerson= new Person ("Thor", "Odinson")
console.log(firstPerson.sayName())

And below an example of a method creation from outside the scope of a class using a prototype:

class Person {
   constructor(fName, lName) {
      this.firstName = fName;
      this.lastName = lName;
   }
}
Person.prototype.sayName = function() {
   return `My Name is ${this.firstName} ${this.lastName}`
}
const secondPerson= new Person ("Tony", "Stark")
console.log(secondPerson.sayName())

A very important thing to note is that using prototype to add a method to a class doesn't change the structure of the class. So logging the object won't render the method. But the method is available to all subclasses and instances of that class.

Fletafletch answered 19/4, 2022 at 10:37 Comment(3)
So basically, by adding things to a class's or non-bound function's .prototype like above, you're adding those things to every single instance of the class or function, including those which have already been created, except for the properties of the instances which have been assigned since their instantiation (new). That is to say that, essentially, the prototype properties of a class or function are the "fallback" properties, if they haven't been set on the instance.Trevar
And if they have been set on the instance, even if you later assign or re-assign the property to the prototype, it will not be rewritten on the already-instantiated instances... It's important also to understand that there might be some caveats to manually modifying .prototype in the cases where you're doing atypical things with your types, like iterating through or copying from prototypes...Trevar
For more information, see here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… developer.mozilla.org/en-US/docs/Web/JavaScript/… developer.chrome.com/blog/smooshgateTrevar
T
3

You can use Object.setPrototypeOf.

Example:

// A class…
class Someone {
  constructor(qui){
    this.qui = qui
  } 
}

// A mixins with new methods
class MyMixins {
  says(quoi){
    console.log(this.qui + " says "+ quoi)
  }
  eats(quoi){
    console.log(this.qui + " eats "+quoi)
  }
}

// An instance…
const marion = new Someone("Marion")

// This fails…
//marion.says("hello!")
//marion.eats("potatoes")

//-----> Here's the trick <------
Object.setPrototypeOf(Someone.prototype, MyMixins.prototype);

// This pass…
marion.says("hello!")   //=> "Marion says hello!"
marion.eats("potatoes") //=> "Marion eats potatoes"
Trula answered 2/9, 2022 at 7:2 Comment(0)
R
2

I know it's a bit late, but would this have solved your problem back then?

class XWithY extends X {
  constructor() {
    super()
  }
  y() {
    console.log('y')
  }
}

const xwy = new XWithY();

console.log(xwy instanceof X); // outputs true
Resolved answered 15/3, 2022 at 21:21 Comment(1)
No this is not adding a method to an existing class, this is creating an instance and adding a method to that. However, this may be the better method of doing things.Abiding

© 2022 - 2024 — McMap. All rights reserved.