JavaScript中的动态实例化

编程入门 行业动态 更新时间:2024-10-23 15:33:19
本文介绍了JavaScript中的动态实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

除了eval之外,还有其他方法可以使用变量参数列表来实例化对象吗?

Apart from eval, is there any other way to instantiate an object using variable argument list?

例如: var foo = instantiate(className) ,[arg1,arg2,...])

推荐答案

你可以用一个实例化一个对象变量参数列表如下:

You can instantiate an object with a variable argument list like this:

function instantiate(className, args) { var o, f, c; c = window[className]; // get reference to class constructor function f = function(){}; // dummy function f.prototype = c.prototype; // reference same prototype o = new f(); // instantiate dummy function to copy prototype properties c.apply(o, args); // call class constructor, supplying new object as context o.constructor = c; // assign correct constructor (not f) return o; }

附注:你可以希望传递对类构造函数的直接引用:

Side note: you may wish to pass a direct reference to the class constructor function:

var foo = instantiate(Array, [arg1, arg2, ...]); // Instead of: var foo = instantiate("Array", [arg1, arg2, ...]);

...这使得它与非全局函数兼容。

... which makes this compatible with non-global functions.

更多推荐

JavaScript中的动态实例化

本文发布于:2023-08-04 17:34:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1298262.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   动态   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!