2

Say I have the following code - and by "I" I mean that its not my code and I cannot remove the new operation. I only received the instance of foo after its instantiated.

var foo = new function() {
    this.bar = 'baz';
}

Is it possible to get the original function and effectively perform another new on it? If so, are there cases where it would not be a clean clone?

var secondFoo = ...foo...
secondFoo.bar = 'qux';

foo.bar       // 'bad'
secondFoo.bar // 'qux'

2 Answers 2

4

You can, objects expose their constructor in the constructor property:

a = new function(){ this.foo = Math.random()}
>> Object {foo: 0.11541059240698814}

a.constructor
>> function(){ this.foo = Math.random()}

b = new a.constructor
>> Object {foo: 0.867641115328297}

But most likely, you wouldn't want to.

Constructors are blue prints for creating new instances. Its not idiomatic to pull from an instantiated object over calling the constructor itself.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, that's the answer I was looking for. I will make it as correct once SO lets me.
@ElliotChance, great! Glad I could help.
Do you know if this is clean in terms of changes made to the state of the new instance would be completely isolated from the old instance? Ignoring anything that points directly to something outside the constructor.
@ElliotChance It's clean, unless you modify their shared prototype. Object.getPrototypeOf( b ).x = 'lol'; a.x === 'lol';. Of course you can't modify a's foo like that (you can't modify any of a's direct properties through b), only new properties, or ones that end up getting deleted from a will be visible through the prototype chain.
-1

Remove the new operator.

var foo = function() {
    this.bar = 'baz';
}

You can now instantiate new objects from the constructor foo.

var instance1 = new foo();
var instance2 = new foo();

instance1.bar = 'test';

console.log(instance1.bar); // 'test'
console.log(instance2.bar); // 'baz'

5 Comments

I realise this, but I only receive the instance not the original function.
The original function is saved to the variable foo.
I mean to say that I do not have control over the original function or control how it's instantiated. I only receive the instance which I wish to make a copy of for stubbing - if I were to modify the original object the change wouldn't be isolated.
Ahh I see, I misunderstood you're question.
That's OK, my fault, after rereading my question I realised that wasn't clear so I clarified it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.