1

I'm given an instance "aNode" of a prototype called "Node". Following this discussion, I attempt to:

var newNode = clone(aNode);

The clone function goes like:

function clone(obj) {
    if (null == obj || "object" != typeof obj) return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
    }
    return copy;
}

Despite obj.consturctor() properly refers to aNode's constructor, copy is "underfined". Can't find why :(

Is this method wrong, or am I missing something :) ?

Thanks, J.

Edit: here is what the Node prototype looks like:

Node.prototype = new PhysicsNode();
Node.prototype.constructor=Node;

function Node() {

    PhysicsNode.call(this);

    this.setBounds(0, 0, 0, 0);
    this.createStaticBody();
}
Community
  • 1
  • 1
Jem
  • 6,226
  • 14
  • 56
  • 74

2 Answers2

2

Ok. Here

var copy = obj.constructor();

is just a function call and constructor function Node does not return anything. You have to use new keyword to create new object.

var copy = new obj.constructor();
Diode
  • 24,570
  • 8
  • 40
  • 51
  • All right! Thanks Diode :-) What's the best practice, have your constructor return something, or not? – Jem Apr 11 '12 at 08:19
1
var copy = obj.constructor();

This line takes the constructor of obj, calls it and assigns the result to copy.

As obj is a Node, according to the line Node.prototype.constructor=Node; it holds that obj.constructor === Node.

Look at the function Node:

function Node() {

    PhysicsNode.call(this);

    this.setBounds(0, 0, 0, 0);
    this.createStaticBody();
}

This function is a constructor, it has to be called with the new keyword. If it is not called with the new keyword, it is just a regular function. As there is no return statement, this function returns nothing.

Therefore,

var copy = obj.constructor();

assigns nothing to obj, so obj is undefined.

Finally,

return copy;

you return this undefined value from your clone function.

Imp
  • 8,409
  • 1
  • 25
  • 36
  • Thanks for your answer. Is it a good practice to have your constructor (prototype wise) return the actual object? Inheritance might make this tricky :( – Jem Apr 11 '12 at 08:21
  • 1
    No. If you call `var x = new MyConstructor();`, the `new` keyword creates a new object and sets `this` to this new object. So whatever `MyConstructor()` does (e.g. `this.property = value`) relates to the new object. You don't return the object from the constructor - the `new` keyword takes care of this. – Imp Apr 11 '12 at 09:12