Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
164
rated 0 times [  171] [ 7]  / answers: 1 / hits: 68340  / 15 Years ago, fri, october 16, 2009, 12:00:00

I think the following code will make the question clear.



// My class
var Class = function() { console.log(Constructor); };
Class.prototype = { method: function() { console.log(Method);} }

// Creating an instance with new
var object1 = new Class();
object1.method();
console.log(New returned, object1);

// How to write a factory which can't use the new keyword?
function factory(clazz) {
// Assume this function can't see Class, but only sees its parameter clazz.
return clazz.call(); // Calls the constructor, but no new object is created
return clazz.new(); // Doesn't work because there is new() method
};

var object2 = factory(Class);
object2.method();
console.log(Factory returned, object2);

More From » oop

 Answers
75

Doesn't this work?


function factory(class_, ...arg) {
return new class_(...arg);
}

I don't understand why you can't use new.


[#98496] Tuesday, October 13, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kamronr

Total Points: 749
Total Questions: 110
Total Answers: 122

Location: Dominica
Member since Sat, Nov 5, 2022
2 Years ago
kamronr questions
Mon, Dec 21, 20, 00:00, 3 Years ago
Fri, Oct 16, 20, 00:00, 4 Years ago
Sat, Oct 3, 20, 00:00, 4 Years ago
Sun, Jul 28, 19, 00:00, 5 Years ago
;