Since JavaScript has no classes, let me reformulate your question: how to create a new object based on an existing object without using a new keyword?
Here is a method that does not use "new". This is not strictly a “new instance”, but the only way I could think of was not to use a “new one” (and does not use any ECMAScript 5 features).
You can get fancy and install a prototype, but then you get into cross-browser issues, and I'm trying to keep it simple. You can also use "hasOwnProperty" to filter the properties that you add to the new object.
There are other ways to use the "new", but it seems to hide them. Here is the one that takes from the Object.create function in JavaScript: Good details of Douglas Crockford :
//Another version the does use 'new' but in a limited sense function factory(clazz) { var F = function() {}; F.prototype = clazz; return new F(); }; //Test var orig = { prop1: "hello orig" }; var testObj2 = factory(orig); console.log(testObj2.prop1); //"hello orig"
EcmaScript 5 has an Object.create method that will do it much better, but is only supported in new browsers (e.g. IE9, FF4), but you can use polyfill (something that fills the cracks) like ES5 Shim to get implementation for older browsers. (See John Resig's article on new ES5 features, including Object.create .)
In ES5, you can do it like this:
//using Object.create - doesn't use "new" var baseObj = { prop1: "hello base" }; var testObj3 = Object.create(baseObj); console.log(testObj3.prop1);
I hope this helps
grahamesd Apr 22 '11 at 15:00 2011-04-22 15:00
source share