26

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?

4
  • just for sake of knowledge: I heard that javascript is classless. What does it means? Commented Mar 5, 2016 at 12:14
  • I expected the new method showed in the log, inside the class. Console.log(X) should log the class code. Commented Mar 5, 2016 at 12:14
  • You added method to the prototype, not as own property. Read about difference. Commented Mar 5, 2016 at 12:16
  • 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. Commented Mar 5, 2016 at 18:27

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

I need y acting like x. For example, when I log X it must print Both x and y inside X.
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.

3 Comments

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.
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...
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"

Comments

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.