March 10, 2013

How to create a new object from an existing one?

Question by defunct

This doesn’t work, and I have no idea how to fix it

function bar() {...}

function foo() {
    this = new bar();

    this.newfunction = function() {...};
    this.newvalue = "foobar";
}

var foobar = new foo();

Thanks in advance,

Answer by dfsq

Are you trying to inherit from bar? Then you can borrow its constructor and all its own properties using call (or apply):

function bar() {...}

function foo() {
    bar.call(this);
    this.newfunction = function() {...};
    this.newvalue = "foobar";
}

var foobar = new foo();

Answer by Starx

Do not use this to represent another object.

function bar() {...}

function foo() {
    var bar = new bar();

    bar.newfunction = function() {...};
    bar.newvalue = "foobar";
}

var foobar = new foo();

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!