问题描述
我使用以下函数从参数数组中创建JavaScript中的函数实例:
I use the following function to create instances of functions in JavaScript from an array of arguments:
var instantiate = function (instantiate) {
return function (constructor, args, prototype) {
"use strict";
if (prototype) {
var proto = constructor.prototype;
constructor.prototype = prototype;
}
var instance = instantiate(constructor, args);
if (proto) constructor.prototype = proto;
return instance;
};
}(Function.prototype.apply.bind(function () {
var args = Array.prototype.slice.call(arguments);
var constructor = Function.prototype.bind.apply(this, [null].concat(args));
return new constructor;
}));
使用上述功能,您可以按以下方式创建实例(请参见小提琴):
Using the above function you can create instances as follows (see the fiddle):
var f = instantiate(F, [], G.prototype);
alert(f instanceof F); // false
alert(f instanceof G); // true
f.alert(); // F
function F() {
this.alert = function () {
alert("F");
};
}
function G() {
this.alert = function () {
alert("G");
};
}
上面的代码适用于用户构建的构造函数,例如F
.但是出于明显的安全原因,它不适用于Array
之类的本机构造函数.您可能总是创建一个数组,然后更改其__proto__
属性,但是我在Rhino中使用此代码,因此它在那里无法使用.还有其他方法可以在JavaScript中获得相同的结果吗?
The above code works for user built constructors like F
. However it doesn't work for native constructors like Array
for obvious security reasons. You may always create an array and then change its __proto__
property but I am using this code in Rhino so it won't work there. Is there any other way to achieve the same result in JavaScript?
推荐答案
您不能完全继承数组的子类.
但是,您可以使用Object.create
从当前代码中消除很多复杂性(例如).
However, you can use Object.create
to remove a lot of complexity from your current code (ex).
这篇关于使用自定义原型实例化JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!