这是什么字符串;在javascript中,以及它是如何工作的;
我在谷歌上搜索过,但什么也没找到 test.js 有没有更好的用例,这个这是什么字符串;在javascript中,以及它是如何工作的;,javascript,Javascript,我在谷歌上搜索过,但什么也没找到 test.js 有没有更好的用例,这个这个[this.heroVar]()有效,请解释, 这是否也会添加。在'this'和'[]'之间添加类似this.hero1()在Javascript类中是一个对象,所以 class Hero(){ heroVar = 'hero1' hero1() { alert('I am Hero 1'); } onClick(){ this[this.heroVar](); //this.heroVar va
这个[this.heroVar]()代码>
有效,请解释,
这是否也会添加。在'this'和'[]'之间添加类似
this.hero1()
在Javascript类中是一个对象,所以
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()
}
}
有两种方法可以访问对象的属性:点表示法(
foo.bar
)和括号表示法(foo[…]
,其中…
可以是任何表达式)。在这种情况下,this.heroVar
解析为的值用作访问this
的属性名。有两种方法可以访问对象中的属性:。[]通过这样做,[]您将计算传递的值,因此这里您给出一个字符串,该字符串等于您可以直接执行的函数this[this.heroVar]()
this
=当前对象,[]
访问属性/函数,this.heroVar
是一个字符串,它等于函数名,()
您执行函数。
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()
}
}