gpt4 book ai didi

javascript - 如何使用变量访问 javascript 对象方法?

转载 作者:行者123 更新时间:2023-11-28 21:15:46 25 4
gpt4 key购买 nike

Possible Duplicate:
Get property of object in JavaScript

var Terminal = function() {
this.walk = function() {
alert('hello');
}
this.go = 'walk';
this.move = 'walk';
}

var term = new Terminal();
var fn = 'walk';
if (term.hasOwnProperty(fn)) {
term.{fn};
}

如何使用字符串“walk”运行 term.walk() 方法?

最佳答案

有几种方法。最简单的是

term[fn]();

或者另一种选择

var funcObj = term[fn];
funcObj.apply(term);

关于javascript - 如何使用变量访问 javascript 对象方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7654327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com