How to access parameters received from a class in an external javascript function?

Asked

Viewed 324 times

0

How can I access parameters received from a class outside its scope, as in the function below. Or is there another better way to do this?

helper.js

class Helper {

    constructor(user) {
        this.user = user;
    }
}

rebeceUser function () {
 // recebe user
}

game js.

new Helper("João");

2 answers

0


Put input parameters as function argument, for example:

class Helper {

    constructor(user) {
         this.user = user;
     }
 }

rebeceUser function (variavelQualquer) {
    console.log(variavelQualquer);
 // recebe user
}

When you call the class method, just put a variable or constant as a parameter between the parentheses of the method

user = "João"
helper = new Helper(user);
helper.recebeUser(user);

But analyzing the method name, I think you want to "welcome" the user of the helper class, for this you do not need a parameter in the function, but just call the attribute that received value in the constructor, would look like this:

class Helper {

    constructor(user) {
         this.user = user;
     }
 }

rebeceUser function () {
    console.log("Bem Vindo " + this.user);
}

-

user = "João"
helper = new Helper(user);
helper.recebeUser();
//Será impresso no console "Bem Vindo João"

(ah, and if they are in different files, you will need to reference each other, in this case the helper.js within the game.js)

  • Returns "Welcome Undefined", as it is in different files, I’m referencing the helper in the game. Still it doesn’t work.

  • If you can access the class method within game.js, then an instance of the class is inside, as the class is instantiating?

  • class helper { constructor(user) { this.user = user; } } Function rebeceUser() { console.log("Welcome " + this.user); } module.Exports = Helper; game.js: Let helper = require('. /helper'); new helper("John");

  • Remember that new returns the reference, if it is not assigning new to anywhere, the reference is empty, and the user object used in the constructor is lost

  • then I pass to the return function?

  • You pass the object reference to a variable, and access the class methods through this variable: "Variable Let = new Helper("John") ", -- " variable.receivedUser() "

Show 1 more comment

0

I hope I have understood your question. There goes:

After instantiating the Helper class, just use .user to access the property.

class Helper {
  constructor(user) {
    this.user = user;
  }
}

var helper = new Helper('João');
console.log(helper.user); // João

If you want the function:

class Helper {
  constructor(user) {
    this.user = user;
  }
}

function recebeUser(objetoHelper) {
  return objetoHelper.user;
}

var helper = new Helper('Maria');
console.log( recebeUser(helper) ); // Maria

Browser other questions tagged

You are not signed in. Login or sign up in order to post.