Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/392.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
这是什么字符串;在javascript中,以及它是如何工作的;_Javascript - Fatal编程技术网

这是什么字符串;在javascript中,以及它是如何工作的;

这是什么字符串;在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

我在谷歌上搜索过,但什么也没找到

test.js

有没有更好的用例,这个
这个[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()
 }
}