If I want to run a function within another function I can pass in some of the arguments like so:
function applyFunc(type) {
myNamespace[type].apply(this, arguments.splice(1));
}
But is there a similar method (or really simple workaround) for instantiating a new object, i.e. pass the outer arguments into the inner function, but using the new keyword too?
function newObj(type) {
new 开发者_如何学编程myNamespace[type].apply(this, arguments.splice(1)); //apply doesn't work here
}
Yes, it should work. If it doesn't in your code, you may consider using Array.prototype.slice.call(arguments,1)
(or [].slice.call(arguments,1)
) in stead of arguments.splice(1)
. Here's some test code, also to be found in this jsfiddle snippet:
function C(){}
C.prototype.fun = function(){
alert('hello'+[].slice.call(arguments).join('\n'));
};
function newf(t){
new C()[t].apply(this,[].slice.call(arguments,1));
}
new C().fun.apply(null,[1,2,3]); //works
newf('fun',1,2,3); //works
精彩评论