简体   繁体   中英

Can I access functions variables?

On clicking button I want some function to have its variables defined, is that possible?

button.addEventListener("click", function(){
   x.name = "john";
   x.lastname = "doe";
});

function x(){
   name = "";
   lastname = "";
} 

How to make function x return name and lastname defined in event listener?

On clicking button I want some function to have its variables defined, is that possible?

How functions work is that you define parameters for the function, and then populate the values of those parameters with arguments to the function. This effectively creates variables in the scope of the function with the values of the arguments you provided.

button.addEventListener("click", function(){
   x("john", "doe");
});

function x(name="", lastname=""){
  console.log(name, lastname);
} 

Here I also added default values for the parameters to equal an emtpy string, just in case not enough arguments were sent.


How to make function x return name and lastname defined in event listener?

Your use of the word "return" is confusing, since functions can return values, but you seem to actually want to assign the values to the variables.

In case you did want to return the same values back, you'd use a return statement with an object to deliver the same values back, but I don't think that's what you were after.

You can redefine x within click handler to set default parameters for the function. Note, "name" is a property of window , adjusted identifier to _name

 const button = document.querySelector("button"); button.addEventListener("click", function() { x = function x(_name = "john", lastname = "doe") { console.log(_name, lastname) } x() }); function x(_name, lastname) { console.log(_name, lastname) }
 <button>click</button>

Writing something like this means that the anonymous function will be called on click events

button.addEventListener("click", function(){
   x.name = "john";
   x.lastname = "doe";
});

it's the same as writing

function onClickListener(){
   x.name = "john";
   x.lastname = "doe";
}

button.addEventListener("click", onClickListener);

but nothing will be reading the response from the onClickListener function, so no you can not return from the function. You can do this instead

var x = {};
function onClickListener(){
   x.name = "john";
   x.lastname = "doe";
}
button.addEventListener("click", onClickListener);

This is ugly code using globals but it should work. Once the cick event is calld the global x var will have the new values

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