What is this['string'](); in javascript and how it works; [duplicate] - javascript

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 2 years ago.
I searched in google but i could not find anything
test.js
class Hero(){
heroVar = 'hero1'
hero1() {
alert('I am Hero 1');
}
onClick(){
this[this.heroVar](); //this.heroVar value gets substituted with hero1
}
}
Is there any better use case,how this this[this.heroVar](); works,please explain,
does this also adds '.' in between 'this' and '[]' like this.hero1()

In Javascript class is an Object so
class Hero(){
heroVar = 'hero1'
hero1() {
alert('I am Hero 1');
}
onClick(){
this[this.heroVar](); //this.heroVar value gets substituted with hero1
// equal with this['hero1']()
// equal with hero1()
}
}

Related

Is it possible to construct a class instance from a.classname string with JavaScript? [duplicate]

This question already has answers here:
Create object from class name in JavasScript ECMAScript 6
(8 answers)
Dynamically loading a typescript class (reflection for typescript)
(10 answers)
Closed 3 months ago.
I am creating a solution in TypeScript/Javascript with an extension mechanism. The extensions will all be classes extending a provided abstract class and a configuration
file will contain the class name and JSON to pass to the constructor. The extensions to be loaded will be defined in a configuration file.
However, I can't find a way to instantiate an instance of a class from the name of the class.
You could key an object by the class names with the relevant constructors assigned as values.
class Class1 {
constructor(val) {
this.val = val;
}
}
const classes = {
Class1
}
const class1Instance = new classes["Class1"]('val1');
console.log(class1Instance.val)
This is an example of instantiating the class object using the string class name. But it looks pretty unsafe and weird to me.
class c1 {
constructor(m) {
this.message = m;
}
showme() {
console.log(`It's class c1! Message: ${this.message}.`);
}
}
const className = 'c1';
const constructorParams = '"instance B of class c1"';
const b = eval(`new ${className}(${constructorParams })`);
b.showme();

How can i use argument with '.' operator? [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 1 year ago.
I use React with CSS Module and My code have many repetitive line.
So, I use function to make simple. here is my code.
const SassComponent = () => {
function stylesBox(color) { return `${styles.box} ${styles}.${color}` }
return (
<div className={styles.SassComponent}>
<div className={stylesBox('red')} />
<div className={`${styles.box} ${styles.orange}`} />
<div className={`${styles.box} ${styles.yellow}`} />
<div className={`${styles.box} ${styles.green}`} />
.....
There is my problem when i use 'color' argument with '.'operator. It doesn't work!
How can i fixed it?
Thank you for reading.
Try:
${styles[color]}
instead of
${styles}.${color}

Could someone poin-out why this works (JS , .bind() ) [duplicate]

This question already has answers here:
addEventListener calls the function without me even asking it to
(5 answers)
Accessing an object's property from an event listener call in JavaScript
(6 answers)
Closed 1 year ago.
can someone point out why the next code as soon as I open the live server webpage prompts me to input the number ( the one without .bind()) while the one with bind works flawlessly?
let chooseNumber;
const poll = {
question: ' What is your favorite programming language?',
options: ['0 : JavaScript', '1:Python', '2: Rust', '3:C++'],
//This generates [0,0,0,0]. More In the next section :D
answers: new Array(4).fill(0),
registerNewAnswer: function () {
chooseNumber = prompt(`${this.question} \n ${this.options}`);
if (chooseNumber >= 0 && chooseNumber < 4) {
this.answers[chooseNumber] = this.answers[chooseNumber] + 1;
}
console.log(this.answers);
console.log('Munem');
},
};
document
.querySelector('.poll')
.addEventListener('click', poll.registerNewAnswer.bind(poll)); //works
//
// document
// .querySelector('.poll')
// .addEventListener('click', poll.registerNewAnswer());
//doesn't work

selecting tag with a specific attribute(only) [duplicate]

This question already has answers here:
Exclusive CSS selector
(3 answers)
Closed 3 years ago.
I have the following document structure in :
...
...
<span class="clblue redcl turbocl">something</span>
<span class="clblue redcl turbocl">something</span>
<span class="clblue">something</span>
<span class="clblue">something</span>
...
...
In JavaScript (only) I want:
document.querySelectorAll("span.clblue") to give span with ONLY 'clblue' class NOT all the span(s) with 'clblue' and also other classes.
If you want to match a single class only rather than that class among others, you can use an attribute selector:
document.querySelectorAll('span[class="clblue"]');
With CSS select only one class name,
span[^="clblue"][$="clblue"] { ... }
Then We select it with JS,
let x = document.querySelectorAll("span[class^=clblue][class$=clblue]"); // NodeList
// x[0], x[1]... x[n]
What about filtering out the querySelectorAll value?
let items = document.querySelectorAll(".clblue");
let filtered = Array.prototype.filter.call(items, function(node) {
return node.classList.length === 1;
});

Run function passed from data attribute [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 7 years ago.
I want to be able to run a function that is passed by name from a data attribute on the HTML side. I've tried the following below.
HTML:
<div class="generic-select" data-help-on-shown="genericFunction" >
</div>
Javascript:
function genericFunction() {
console.log("generic function called");
}
Other Javascript (separate file):
//stepEl is correct divider from above
var genFunction = typeof (stepEl.data("helpOnShown")) === "undefined"
? null
: stepEl.data("helpOnShown");
//this prints "genericFunction" as expected
console.log("genFunction = " + genFunction);
if (genFunction) {
genFunction(); //gives error!
}
However, this gives me an error. Is there a way to call a function by a string name?
If the function is "global", it exists as a property of window:
window[functionname]()

Categories

Resources