0

I have a simple class named B which have a basic property. I have a prototype method named print which will print that Class property. Now everything works fine if i use normal function syntax. I want to use arrow function syntax for my prototype am already aware of that this inside arrow function will refer to global(window) object. I want this to bind my Class. Is there any way how can i achieve it?

class B {
   constructor() {
    this.name ="kannan";
  }
}

B.prototype.print = function(){
    console.log(this);
    console.log(this.name);
 }

 let name = new B();
 name.print() //Prints my name and works correctly

However, if I try with arrow syntax

 B.prototype.print = () => {
    console.log(this);
    console.log(this.name);
 }

 name.print() //prints this as a global window object

How can I achieve to print my name with arrow syntax?

Kannan T
  • 1,639
  • 5
  • 18
  • 29
  • 1
    Syntax is there to express a purpose. Don't make a specific syntax itself your purpose. – trincot Jun 27 '18 at 18:56
  • You can't use arrow functions inside the *prototype* as they are contextless. You could however declare them inside the constructor, but thats against the sense if inheritance. – Jonas Wilms Jun 27 '18 at 18:57

1 Answers1

0

Im not 100% sure but normal function syntax takes its context from where it is run. Arrow syntax takes its context from where it is initialized.

try setting the proto inside the constructor and it should print 'this' as your instance of your class.

alternative: write print as a function of the class and you should not have the problem at all.

I dont think using prototype on a class is pretty when working with an instance of this class.

tabulaR
  • 300
  • 3
  • 13