How to Access This Variable

How do I access a variable declared inside a function

Good option:

Turn getInput() into a helper function. After all, it doesn't do anything but manipulate the value of a DOM element, which is accessible any time - it doesn't need to be hooked onto your button's onClick event directly.

// returns the processed input
function getInput() {
var fetchedDate = document.getElementById('dob').value;
fetchedDate = fetchedDate.split('/').reverse('').join('-');
return fetchedDate.replace(/\s+/g, '');
}

// called from button onClick
function getValues() {
var date = getInput();
// other code that would use `fetchedDate`
}

Decent option:

Make getValues() accept a parameter so that you can simply pass fetchedDate to it.

function getInput() {
var fetchedDate = document.getElementById('dob').value;
fetchedDate = fetchedDate.split('/').reverse('').join('-');
fetchedDate = fetchedDate.replace(/\s+/g, '');
getValues(fetchedDate);
}

function getValues(fetchedDate) {
// do stuff with fetchedDate
}

Okay option:

Declare the variable in a higher scope so that you can access it from other functions freely.

var fetchedDate;

function getInput() {
fetchedDate = document.getElementById('dob').value;
fetchedDate = fetchedDate.split('/').reverse('').join('-');
fetchedDate = fetchedDate.replace(/\s+/g, '');
getValues();
}

Poor option:

Make the variable truly "global" by attaching it to the Window object. This is the default behavior if you don't specify a declaration with var.

function getInput() {
fetchedDate = document.getElementById('dob').value;
fetchedDate = fetchedDate.split('/').reverse('').join('-');
fetchedDate = fetchedDate.replace(/\s+/g, '');
getValues();
}

How to access a variable declared on function scope from inside subscribe in angular

Overlapping function problems can prevent the value of this from disappearing by storing references to this of the parent function using the scope chain.

so using the word self, context, $this or anything else when you assign the value of this to it. it is locked in place like any other regular variable.

somethingCollection: TypeSomething[]
...
public deleteSomething(something: TypeSomething): void {
let self = this;
this.someAPI.deleteSomething(something.id).subscribe( (res) => {
self.somethingCollection // access somethingCollection....
// this.somethingCollection is undefined
}
}

How can I access a variable that is out of a class' scope?

The (more-or-less) standard approach for things like this is to use some kind of variant of the MVC design pattern. The key thing here is to have a separate class ("model") that holds the data; you can then pass a single instance of that class to any actor that needs access to it.

public class Model {

private int currentlySelectedValue ;

// probably other properties here...

public void setCurrentlySelectedValue(int value) {
currentlySelectedValue = value ;
}

public int getCurrentlySelectedValue() {
return currentlySelectedValue ;
}
}

Then you can do:

public class Cell extends StackPane{

private final Model model ;

private Text text; //displays the number inside the cell
private Rectangle rect; //visual element for the cell

/**
* Default Constructor for Cell
*/
public Cell(Model model) {
this.model = model ;
text = new Text("");
text.setFont(Font.font(30));
rect = new Rectangle(50, 50);
rect.setStyle("-fx-fill: white; -fx-stroke: black; -fx-stroke-width: 1;");
this.getChildren().add(rect);
this.getChildren().add(text);

this.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent t) {
text.setText("" + model.getCurrentlySelectedValue());
}
});
}
}

and

public class Main extends Application {

private int selectedNum = 0;

@Override
public void start(Stage primaryStage) {

Model model = new Model();

try {

Group root = new Group();
Cell cell1 = new Cell(model);
cell1.setLayoutX(100);
cell1.setLayoutY(100);
root.getChildren().add(cell1);

Button numSelection[] = new Button[9];
for (int i = 0; i < 9; i++) {
final int j = i + 1;
numSelection[i] = new Button("" + j);
numSelection[i].setLayoutY((i / 3) * 55 + 200);
numSelection[i].setLayoutX((i % 3) * 55 + 630);
numSelection[i].setMinHeight(50);
numSelection[i].setMinWidth(50);
numSelection[i].setFont(Font.font(20));
root.getChildren().add(numSelection[i]);

numSelection[i].setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
model.setCurrentlySelectedValue(j);
}
});
}

Scene scene = new Scene(root,900,500);
primaryStage.setScene(scene);
primaryStage.show();

} catch(Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
launch(args);
}
}

Note that there are some "shortcut" approaches if all you need is one single value; e.g. you could use an IntegerProperty instead of a custom model class. The structure and concept is really the same though.

How to Access a variable in a Shell script

With bash and grep and assuming that the settings file has exactly one line beginning with ROLE=:

#!/bin/bash

admin=master_doc
staff=staff_doc
guest=welcome_doc

cd /setting || exit
role=$(grep '^ROLE=' settings)
role=${role#*=}
echo chmod 555 "${!role}.service"

Drop the echo after making sure it works as intended.

Look into Shell Parameter Expansion for indirect expansion.

How to access variables created in __init__ in another def in the same instance of a class?

class something():
def __init__(self):
self.a = 2

def play(self, b):
return True if self.a == b else False

test = something()
print(test.play(1))

In the __init__ you have to use self.variable and same can be used in other functions too of same class.

how to access a variable that's inside a function

What you are missing is that the returned value must be stored in another variable.
For example,

def test():
x = 1
return x

def main():
z = test()
print(z)

main()

This program will output:

1

You must pass the output of your functions as parameters to the subsequent calls of different functions. I have reworked your code to work like this.

def main():
key_character = get_key_character()
phrase_input = get_string()
sentence_capitalized = sentence_capitalizer(phrase_input)
removed = remove_key_character(key_character, sentence_capitalized)
print(removed)

def get_key_character():
key_character=""
while len(key_character) < 1:
key_character=str(input("Please enter a SINGLE character to act as key? "))

return key_character

def get_string():
phrase_input=str(input("Please enter a phrase or sentence >=4 and <=500 characters: "))
if len(phrase_input) <4 or len(phrase_input)>500:
get_string()
else:
return phrase_input

def sentence_capitalizer(phrase_input):
import re
sentence_capitalized=(re.sub(r"(^|\?|\.|\!)\s*(\w)", lambda q: q[0].upper(), phrase_input))
return sentence_capitalized

def remove_key_character(key_character, sentence_capitalized):
return sentence_capitalized.replace(key_character, "")

main()

How to access a variable from another function in the same class in Angular?

Create your variable as global variable, then you can access it within the class like this.

export class ExecutableVariableNode implements IExecutableNode {

namesSplit: any;

execute(treeNode: ExpressionTreeNode, exprData: ExpressionData): any {
this.namesSplit = treeNode.name.split('.');
let key = this.namesSplit[0];
let contextEntry = exprData.contextEntry.find(_x => _x.name === key);

if (this.namesSplit.length > 1) {
this.evaluateResult(contextEntry.value);
}
}

isPrimitive(test): boolean {
return typeof test !== 'object';
}

// Get Values
evaluateResult(val) {
if (this.getType(val) === ExpressionVariableType.OBJECT) {
return Object.values(val);
}
else if (this.getType(val) === ExpressionVariableType.ARRAY_OF_OBJECTS) {
for (let obs of val) {
for (let n = 0; n < this.namesSplit.length; n++) {
if (this.namesSplit[n] == Object.keys(obs)) {
let result = Object.values(obs);
console.log(result);
break;
}
}
}
}
else if (this.getType(val) === LapsExpressionVariableType.ARRAY_OF_PRIMITIVES) {
throw new StdException('Array of Primitives not allowed!');
}
else if (this.getType(val) === LapsExpressionVariableType.PRIMITIVE) {
throw new StdException('Primtive values not allowed!');
}
}
}

How can i access variables in the main function from other function

No. You'll have to pass a pointer/reference to the function with the way you currently have it written, or set it as a global variable (which is typically frowned upon unless required by the problem scope).

Another potential idea would be to make an object.

class MyClass { 
private:
string key;
public:
string read_from_ram(string& key) {};
};

In this case, key would be accessible from anywhere inside your class.

How to access a variable inside a ListViewBuilder from where the builder is called?

One way to do it is instantiating a TextEditingController from the outside in the itemBuilder and inject it inside the BrandNamesWidget, hold their references in a collection, that way you can grab their content from the outside like this Gist I created for you. This is what your new class would look like:

class BrandNamesWidget extends StatelessWidget {

final TextEditingController? controller;
final String? brandName;
final int? index;

BrandNamesWidget({ this.brandName, required this.index, this.controller });

@override
Widget build(BuildContext context) {

double height = 100;
double width = MediaQuery.of(context).size.width;

return TextField(
controller: controller!,
keyboardType: TextInputType.text,
decoration: InputDecoration(
constraints: BoxConstraints(maxWidth: width * 0.45),
labelText: 'Brand name: ' + index.toString(),
prefixIcon: const Icon(Icons.medication),
labelStyle: TextStyle(
fontSize: height * 0.03,
color: Colors.grey,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(50),
),
),
);
}
}

And this is the parent widget holding on to the TextEditingController references, housing your ListView.builder:


class MyWidget extends StatelessWidget {

List<String> _brandnames = ['Toyota', 'Honda', 'BMW', 'Mercedes'];
List<TextEditingController> controllers = [];

@override
Widget build(BuildContext context) {

controllers = [];

return Column(
children: [
Expanded(
child: Container(
child: ListView.builder(
itemCount: _brandnames.length,
itemBuilder: (BuildContext ctx, int index) {
TextEditingController ctrl = TextEditingController();
controllers.add(ctrl);
return BrandNamesWidget(
brandName: _brandnames[index].toString(),
controller: ctrl,
index: index);
}),
)
),
TextButton(
onPressed: () {

for(var ctrl in controllers) {
print(ctrl.text);
}
},
child: Text('Click me to get their values')
)
]
);
}
}

If you input stuff on the text fields shown, and you click on the button I provided, you'll get their content from a function, thus being able to update Firestore or anything you want. Check it out and let me know.



Related Topics



Leave a reply



Submit