0

I kind of expected the following code to work - I wanted a clone that wasn't recursive.

It didn't...

Why, and what can I do to get around it?

person=new Object();
person.firstname="John";
person2 = new person; //Expected a new person object with firstname john    

"TypeError: object is not a function"

and the same for

person2 = new person()
Alex
  • 5,674
  • 7
  • 42
  • 65
  • `new` is used on a constructor function and clones its `prototype` object. May as well just write your own cloning function… – Ry- Mar 10 '13 at 22:00
  • Bah, I over simplified my question. – Alex Mar 10 '13 at 22:04
  • If you need in depth explanations about Javascript object model, I suggest you to read [Javascript Garden](http://bonsaiden.github.com/JavaScript-Garden/). Everything about objects, prototype, constructors and inheritance is explained. – Fabien Quatravaux Mar 10 '13 at 22:18
  • I haven't read it in like 3 months, maybe I should re-read it... again. – Alex Mar 10 '13 at 22:19

2 Answers2

3

The new operator in Javascript is applied to a function to create a new object with that functions prototype chain applied to the new object. You can't apply it to an object directly.

If you want to clone an object in javascript its not a simple process. You can see this answer for a list of possibilities: How do I correctly clone a JavaScript object?. The simplest method is to use jQuery and $.extend. But you can also write a common Javascript solution. If you only want to use it for a specific type of object it may be fairly simple.

If you want to use new correctly you can create a constructor function like this

var Person = function() {
 this.firstname = "John";
};
var person1 = new Person();
var person2 = new Person();

That will create 2 new Person objects, independent of each other.

Community
  • 1
  • 1
Ben McCormick
  • 25,260
  • 12
  • 52
  • 71
1
var Person = function() {
 this.firstname = 'John';
};

person2 = new Person();

The error thrown provides you with valuable information (a rarity in JavaScript, for sure) - you can only use the new operator when applying it to a function, not any other object.

Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100