user905864
user905864

Reputation:

Convert arguments into new object parameter without cloning the object?

I want to create a new object with parameters from 'arguments', but I don't know how to or even possible to convert it directly without cloning. Here's how it is possible using a clone:

function theClass(name, whatever) {
        this.name = name;
        this.whatever = whatever;
    }

// I need to use the arguments passed from this function but without using clone
// as shown.
function doSomething()
{
    function clone(args) {
        theClass.apply(this, args);
    }

    clone.prototype = theClass.prototype;

    return new clone(arguments);
}

// Usage expectation.
var myNewObject = doSomething("Honda", "motorbike");

console.log(myNewObject.name);

However, this suffers on performance because each time you call doSomething, you have to create a clone just to pass that arguments to be applied in it from theClass.

Now I want to pass that arguments without passing to a cloned object, but I don't know how to convert it directly.

Any idea?

Note: As clarified by kaminari, the parameters passed are not strictly 'name' and 'whatever', but could be anything depends on the object I want to create. 'theClass' in the code is merely an example.

Thanks.

Upvotes: 0

Views: 74

Answers (2)

kaminari
kaminari

Reputation: 306

EDIT: In light of the intended use of these functions:

Probably your best option on maintaining your intended behavior is to implement your function in the following way:

function theClass(options){
   this.name = options.name || ''; //or some other default value
   this.whatever = options.whatever || '';
};

function doSomething(options){
   options = options || {};
   return new theClass(options);
};

With this implementation in mind, the code you supplied in "usage expectation" would look like this:

var myNewObject = doSomething({name: "honda", whatever: "motorbike"});

console.log(myNewObject.name);

In this manner, theClass can support as many or as few parameters as need be (only depends on what's supplied in the object and what you choose to extract from it) and similarly, the wrapper doSomething can be given as many or as few options as desired.

Upvotes: 1

Bergi
Bergi

Reputation: 665130

this suffers on performance because each time you call doSomething, you have to create a clone just to pass that arguments to be applied in it from theClass.

Simply define the clone function outside of doSomething, and it won't get recreated every time:

function theClass(name, whatever) {
    this.name = name;
    this.whatever = whatever;
}

function clone(args) {
    theClass.apply(this, args);
}
clone.prototype = theClass.prototype;
function doSomething() {
    return new clone(arguments);
}

Upvotes: 0

Related Questions