gpt4 book ai didi

javascript - 用数组初始化对象,Javascript

转载 作者:行者123 更新时间:2023-11-29 22:08:47 24 4
gpt4 key购买 nike

当我有一个对象时:

var YayanObject = function(var1, var2, var208) {
this.var1 = var1;
this.functiony = function() {
More Functiony stuff :)
}
Do stuff :D
}

我想用 2 个变量调用它:

var1 = "YayanObject";
var2 = [1,"2","Hello world"];

我想调用对象:

window[var1](????);

如何填写问号?

最佳答案

你可以使用 apply :

fun.apply(thisArg[, argsArray]):
  • thisArg: The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.
  • argsArray: An array-like object, specifying the arguments with which fun should be called, or null or undefined if no arguments should be provided to the function.

请注意,如果您不使用严格模式,那么在没有 var 的情况下声明变量会使它们成为全局变量,因此您可以将其用作 window 的属性:

var1 = "YayanObject";
var2 = [1,"2","Hello world"];
window[var1].apply(null, var2); /* Instead of `null` you can use the object
you want to become `this` */

但我建议您在 var1 中存储对构造函数的引用而不是字符串:

var var1 = YayanObject,
var2 = [1,"2","Hello world"];
var1.apply(null, var2);

关于javascript - 用数组初始化对象,Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19336908/

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