栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JavaScript将.apply()与'new'运算符配合使用。这可能吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript将.apply()与'new'运算符配合使用。这可能吗?

使用ECMAscript5可以使

Function.prototype.bind
事情变得非常干净:

function newCall(Cls) {    return new (Function.prototype.bind.apply(Cls, arguments));    // or even    // return new (Cls.bind.apply(Cls, arguments));    // if you know that Cls.bind has not been overwritten}

可以如下使用:

var s = newCall(Something, a, b, c);

甚至直接:

var s = new (Function.prototype.bind.call(Something, null, a, b, c));var s = new (Function.prototype.bind.apply(Something, [null, a, b, c]));

即使基于特殊的构造函数,此方法和基于eval的解决方案仍然是唯一可以正常工作的解决方案

Date

var date = newCall(Date, 2012, 1);console.log(date instanceof Date); // true

编辑

一点解释:我们需要

new
在一个带有有限数量参数的函数上运行。该
bind
方法允许我们这样做:

var f = Cls.bind(anything, arg1, arg2, ...);result = new f();

anything
参数无关紧要,因为
new
关键字reset
f
的上下文。但是,出于语法原因,它是必需的。现在,进行
bind
调用:我们需要传递可变数量的参数,所以就可以了:

var f = Cls.bind.apply(Cls, [anything, arg1, arg2, ...]);result = new f();

让我们将其包装在一个函数中。

Cls
被作为arugment 0传递,它将成为我们的
anything

function newCall(Cls ) {    var f = Cls.bind.apply(Cls, arguments);    return new f();}

实际上,

f
根本不需要临时变量:

function newCall(Cls ) {    return new (Cls.bind.apply(Cls, arguments))();}

最后,我们应该确保这

bind
确实是我们所需要的。(
Cls.bind
可能已被覆盖)。因此,将其替换为
Function.prototype.bind
,我们得到的最终结果如上所述。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/432220.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号