简体   繁体   中英

How to register this inside a function of a method?

How to add this inside this functions of a method. Here is the codes

class Students {
  constructor (name, roll) {
    this.name = name;
    this.roll = roll;
  }
  document () {
     console.log(' this in method ', this);
    //  this inside function 
    function something () {
      // how to bind this inside this something function 
      console.log('this inside a function', this);
    }

    something.bind(this);
    something();
  }
}



const rejoan = new Students('Mohd Rejoan', 963782);

rejoan.document()

I am trying to get this inside the something function. I am trying to bind this function but not working as expected. Well, arrow function works fine but I want to know what's going on. Here is the live version of this codes => https://playcode.io/1038919

I have tryed to get the this object inside a function of a object method in javascript. But it's not working as expected. So I am expecting someone to solve this and explain this to me, how to solve this problem.

bind returns a function, you need to invoke that function

 class Students { constructor (name, roll) { this.name = name; this.roll = roll; } document () { console.log(' this in method ', this); // this inside function function something () { // how to bind this inside this something function console.log('this inside a function', this); } let bindedFunction = something.bind(this); bindedFunction(); } } const rejoan = new Students('Mohd Rejoan', 963782); rejoan.document()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM