I have saved a property _data in prototype as a definition for all created objects.
function A() {}
A.prototype._data = [];
Now all objects created from A have property _data.
I'd like prototype inheritance, where _data of prototype will have _data values from all prototypes in prototype chain.
Don't know direct way, in this example I use a getter get().
function A() {}
A.prototype._data = [];
A.prototype.add = function(rec) {
this.__proto__._data.push(rec);
}
A.prototype.get = function() {
if(typeof this.__proto__.constructor.prototype.get == 'function')
{
return this.__proto__.constructor.prototype.get().concat(this.__proto__._data);
}
else
{
return this.__proto__._data || [];
}
}
function B() {}
B.prototype = Object.create(A.prototype, { constructor: { value: B }});
B.prototype._data = [];
When I create object a with values aa and object b with value bb, b.get() returns [aa, bb]. And later if _data of prototype A will be extended with aaaa, function b.get() returns [aa, aaaa, bb].
var a = new A(), b = new B();
a.add('aa');
b.add('bb');
console.log(b.get()); // [aa, bb]
a.add('aaaa');
console.log(b.get()); // [aa, aaaa, bb]
// EDITED - _data in A prototype shoud be without B
console.log(a.get()); // [aa, aaaa]
Is it a good (standard) way how to achieve this? I mean using constructor correction while Object.create and reference parent prototype with constructor.prototype?
Here is a demo: http://jsfiddle.net/j9fKP/
Reason for all of this is field definition for scheme in ORM library, where inheritance of schemes is allowed. Child scheme has to have all fields from parent scheme.
I'd like prototype inheritance, where _data of prototype will have _data values from all prototypes in prototype chain.
That's a different thing. "Prototype inheritance" means that if there's a _data property on the current object, it won't go looking further in the chain. Also, it seems to be a kind of issue with nested objects, though I'm not sure what you really want. However, it hardly will make sense to let an array object inherit from another array, if you actually want to concatenate them.
So I think your getter is really fine.
Is it a good (standard) way how to achieve this? I mean using constructor correction while Object.create and reference parent prototype with constructor.prototype
Constructor correction is nice, but actually quite useless (especially if you expect a standard-conform Object.create).
However, in this.__proto__.constructor.prototype either the .__proto__ or the .constructor.prototype is redundant. Since both are either nonstandard or require constructor correction, you should use the standard Object.getPrototypeOf() function to get your prototype object.
With the following very generic solution, you can nest the inheritance (A.proto, B-proto, B-instance, …) arbitrarily deep. Everything inheriting from A.prototype will have an add method which adds _data to the current object, and a get method that traverses the prototype chain and collects all _data:
function A() {
// this._data = []; // why not?
}
A.prototype._data = []; // not even explicitly needed
A.prototype.add = function(rec) {
if (! this.hasOwnProperty("_data")) // add it to _this_ object
this._data = [];
this._data.push(rec);
}
A.prototype.addToAllInstances = function(rec) {
Object.getPrototypeOf(this).add(rec);
}
A.prototype.get = function() {
var proto = Object.getPrototypeOf(this);
var base = typeof proto.get == 'function' ? proto.get() : [];
// maybe better:
// var base = typeof proto.get == 'function' && Array.isArray(base = proto.get()) ? base : [];
if (this.hasOwnProperty("_data"))
return base.concat(this._data); // always get a copy
else
return base;
}
function B() {
A.call(this);
}
B.prototype = Object.create(A.prototype, { constructor: { value: B }});
B.prototype._data = []; // not even explicitly needed
Example usage:
var a = new A();
var b = new B();
a.add('ai');
a.get(); // [ai]
a.addToAllInstances('ap'); // === A.prototype.add('ap');
a.get(); // [ap, ai]
new A().get(); // [ap]
b.get(); // [ap]
b.prototype.get(); // [ap]
b.add('bi');
b.get(); // [ap, bi]
a.addToAllInstances('aap');
b.addToAllInstances('bp');
b.get(); // [ap, aap, bp, bi]
function A() {}
A.prototype._data = [];
A.prototype.add = function(rec) {
this._data.push(rec);
}
A.prototype.get = function() {
return this._data;
}
function B() {}
B.prototype = Object.create(A.prototype, { constructor: { value: B }});
B.prototype._data = [];
B.prototype.get = function() {
return A.prototype._data.concat(this._data);
}
a.add('aa');
b.add('bb');
console.log(b.get()); // [aa, bb]
a.add('aaaa');
console.log(b.get()); // [aa, aaaa, bb]
Fiddle
I think I have a better understanding of what you want to do now, so I've deleted my earlier answer and am posting this one.
Here's how I think I'd do it (with the caveat that I'm not at all sure that with an even better understanding, a completely different approach wouldn't be better):
function A() {}
A.prototype._Adata = [];
A.prototype.add = function(rec) {
this._Adata.push(rec);
};
A.prototype.get = function() {
return this._Adata;
};
function B() {}
B.prototype = Object.create(A.prototype, { constructor: { value: B }});
B.prototype._Bdata = [];
B.prototype.add = function(rec) {
this._Bdata.push(rec);
};
B.prototype.get = function() {
return this._Adata.concat(this._Bdata);
// Or: return A.prototype.get.call(this).concat(this._Bdata);
};
var a = new A();
var b = new B();
a.add('aa');
b.add('bb');
console.log(b.get()); // [aa, bb]
a.add('aaaa');
console.log(b.get()); // [aa, aaaa, bb]
Fiddle
That way, B isn't reaching too deeply into A's internals.
Related
I would like to follow the inheritance structure shown above. I would like create an engineer using this syntax:
var Mark = new Employee(id).WorkerBee(project).Engineer();
To achieve this syntax, I have to create a nested object following a parasitic inheritance pattern like so:
function Employee(id) {
this.id = id;
this.WorkerBee = function(project) {
this.project = project;
this.Engineer = function() {
...
return this;
};
return this;
};
}
To avoid deep layers of nesting, I am trying to rewrite it using prototypes. How can I rewrite my code to achieve the same goal as above ?
function Employee(id) {
//variables
this.id = id
this.name = "";
this.dept = "general";
//methods
this.getId = function() {
return this.id
}
}
Employee.prototype.WorkerBee = WorkerBee;
function WorkerBee(project) {
//variables
this.projectName = project
this.projects = [];
//methods
this.getProjectName = function() {
return this.projectName
}
return this
}
WorkerBee.prototype.Engineer = Engineer
function Engineer() {
//variables
this.dept = "engineering";
this.machine = "";
//methods
this.getDept = function() {
return this.dept
}
return this
}
var Mark = new Employee("5").WorkerBee("Secret Project").Engineer();
console.log(Mark.getId()) //should print "5"
console.log(Mark.getProjectName()) //should print "Secret Project"
console.log(Mark.getDept()) //should print engineering
UPDATE:
Ok, I understand partially. What is the reason why you want to do this? Do you just want a shortcut for creating multiple instances using multiple statements?
Should the instance of C returned by A().B().C() be any different than the one created with the standard new C()?
If you just want to chain constructors, you can add the context in which they are defined (most likely the global object) to the prototype chain of the created entities. You should be able to do that:
var A = function () {};
A.prototype = Object.create(this);
What this does not eliminate though is the need for the new keyword for instantiation. You would need to do new (new (new A()).B()).C(). I can't think of a different approach than having a helper function which would create constructors which do not require the new keyword:
var define = function (init) {
var Constructor = function () {
if (!(this instanceof Constructor)) {
return new Constructor();
}
if (init) {
init.apply(this, Array.prototype.slice.call(arguments));
}
};
Constructor.prototype = Object.create(this);
return Constructor;
};
The usage is:
var A = define(function (x, y) {
this.x = x;
this.y = y;
});
var a1 = new A(1, 2);
// a1 instanceof A === true
// a1.x === 1
// a1.y === 2
var a2 = A(1, 2);
// a2 instanceof A === true
// a2.x === 1
// a2.y === 2
If you have the constructors A, B and C, you can use the following notations interchangeably:
var a = new A();
var b = new B();
var c = new C();
var a = A();
var b = B();
var c = C();
var b = A().B();
var c = A().C();
var a = B().C().A();
In case of A().B().C(), you do not have access to the instances of A and B.
Can you elaborate a bit more on what is your deal?
OLD ANSWER:
What you have there is madness as you basically merge three constructors and make it seem that `WorkerBee` and `Employee` are actually instantiated while they are not.
I'm not going to question the new A().B().C() notation even though I find it quite messed up.
You probably want to make use of the instanceof operator the following way.
var A = function (x) {
if (!(this instanceof A)) return new A(x);
this.x = x;
};
var B = function (y) {
if (!(this instanceof B)) return new B(y);
this.y = y;
};
var C = function () {
if (!(this instanceof C)) return new C();
};
A.prototype.B = B;
B.prototype.C = C;
You can now call new A() and A(), new B() and B() and new C() and C() interchangeably while achieving the same result as both of the calls always return an instance of the constructor.
new A() instanceof A === true
new A().B() instanceof B === true
new A().B().C() instanceof C === true
Based on the comments, you seem to have the belief that you have to use this odd, verbose mechanism in order to have inheritance between Employee <- WorkerBee <- Engineer (and such), but you don't; normal inheritance is all you need for this:
// ==== Employee
function Employee(id) {
this.id = id;
}
// Add Employee methods to Employee.prototype, e.g.:
Employee.prototype.getId = function() {
return this.id;
};
// ==== WorkerBee, derived from Employee
function WorkerBee(id, project) {
// Inheritance, part 1: Chain to the base constructor
Employee.call(this, id);
// WorkerBee stuff
this.project = project;
}
// Inheritance, part 2: Create the object to use for WorkerBee
// instance prototypes, using Employee.prototype as its prototype.
WorkerBee.prototype = Object.create(Employee.prototype);
WorkerBee.prototype.constructor = WorkerBee;
// Add WorkerBee methods to WorkerBee.prototype, e.g.:
WorkerBee.prototype.getProjectName = function() {
return this.project;
};
// ==== Engineer, derived from WorkerBee
function Engineer(id, project) {
// Inheritance, part 1: Chain to the base constructor
WorkerBee.call(this, id, project);
}
// Inheritance, part 2: Create the object to use for Engineer
// instance prototypes, using WorkerBee.prototype as its prototype.
Engineer.prototype = Object.create(WorkerBee.prototype);
Engineer.prototype.constructor = Engineer;
// Add Engineer methods to Engineer.prototype, e.g.:
Engineer.prototype.getDept = function() {
return "Engineering";
};
// ==== Usage
var mark = new Engineer("5", "Secret Project");
snippet.log(mark.getId()); // "5"
snippet.log(mark.getProjectName()); // "Secret Project"
snippet.log(mark.getDept()); // "Engineering"
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
That's the standard way to do prototypical inheritance using constructor functions in JavaScript (for now; in ES6, you'd use the new class feature, which does basically the same thing, with some syntactic sugar). Just add Manager (derived from Employee) and SalesPerson (derived from WorkerBee).
On old browsers, you may need a partial polyfill for Object.create, which looks like this:
if (!Object.create) {
Object.create = function(proto, props) {
if (typeof props !== "undefined") {
throw "The two-argument version of Object.create cannot be polyfilled.";
}
function ctor() { }
ctor.prototype = proto;
return new ctor();
};
}
There are transpilers for taking ES6 source with class and turning it into ES5 code. There's also my Lineage script, which makes inheritance a lot less verbose.
Here is a simple example of what I want :
var ConstBuilder = function() {
var constructor = function() {} ;
constructor.prototype = {} ;
return constructor ;
} ;
ConstBuilder.prototype = {
add : function(name, value) {
this.prototype[name] = value ;
}
} ;
var A = new ConstBuilder() ;
A.add('test', function() {
console.log('test') ;
}) ;
var a = new A() ;
a.test() ;
This code will fail as A is not an instance of ConstBuilder (because A comes from a returned var constructor = function() {} and won't have the methods defined in its prototype (add).
But this would be useful to modify the super constructor's prototype to have things like :
ConstBuilder.prototype.remove = function(name) {
delete this.prototype[name] ;
} ;
A.remove('test') ;
a.test ; // undefined
Is there a way to have a function as an instance of another ? So this function may implicitely "inherit" all the methods defined in its constructor's prototype.
Or if you have other suggestions, I aim to build modulable constructors - as instances with prototypes are.
Please make sure you have understood the difference between the .prototype property and the internal inheritance-prototype.
The code will fail as A is not an instance of ConstBuilder. Is there a way to have a function as an instance of another?
A is, as every constructor needs to be, a Function. So if you just define your add and remove methods on the Function.prototype, it will work:
Function.prototype.add = function(name, value) {
this.prototype[name] = value;
};
Function.prototype.remove = function(name) {
delete this.prototype[name];
};
function A() {}
A.add('test', function(){console.log('test');});
var a = new A();
a.test(); // test
A.remove('test');
a.test; // undefined
There is no possibility however to let a function inherit from something else than Function.prototype - see Can a JavaScript object have a prototype chain, but also be a function?. If you don't want to modify the native Function.prototype object, you still can use the mixin pattern:
var Constr = (function() {
function add(name, value) {
this.prototype[name] = value;
}
function remove(name) {
delete this.prototype[name];
}
return function mixin(c) {
c.add = add;
c.remove = remove;
return c;
};
})();
var A = Constr(function() {…});
A.add("test", …);
var a = new A();
a.test(); // test
I aim to build modulable constructors
You could use the builder pattern, as you just have seem to tried.
function ConstBuilder() {
this.prototype = {};
};
ConstBuilder.prototype = {
add: function(name, value) {
this.prototype[name] = value;
},
remove: function(name) {
delete this.prototype[name];
},
getConstructor: function() {
var constructor = function() {};
constructor.prototype = this.prototype;
this.prototype.constructor = constructor;
return constructor;
}
};
var A = new ConstBuilder().add('test', function() {
console.log('test');
}).getConstructor();
var a = new A();
a.test(); // test
To remove functions later, you would need to save a reference to the builder.
I think that you are looking for an example of how to do JavaScript's "prototypical inheritance". When JavaScript looks for a property on an object, it first checks the object itself. Next it checks the prototype. However, since everything in JavaScript is an object and the prototype is an object
function Root(){}
Root.prototype.fromRoot = function() { console.log("I'm on Root's prototype."); };
function Child(){}
Child.prototype = new Root();
Child.prototype.fromChild = function() { console.log("I'm on Child's prototype."); };
var r = new Root();
var c = new Child();
r.fromRoot(); // works
c.fromRoot(); // works
c.fromChild(); // works
r.fromChild(); // fails
function a (x,y,construct)
{
if (!construct) return;
this.x=x;
this.y=y;
}
a.prototype.methoda=function ()
{
return x+y;
}
function b (x,y,d,e)
{
a.call (this,x,y,true) //--- this would inherit all own Objects and Properties of a and become own properties of b
this.d=d;
this.e=e;
}
b.prototype=new a (); //--- this would only inherit the prototype, construct becomes false and isnt worked through, which if not would result in adding propertiy x and y to prototype instead of directly to instance of b,
b.prototype.constructor=b;
var test=new b (1,2,3,4);
b.methoda ();
second way
function a (x,y)
{
if (arguments.callee.doNotConstruct) return;
this.x=x;
this.y=y;
}
a.prototype.methoda=function ()
{
return x+y;
}
function b (x,y,d,e)
{
a.call (this,x,y) //--- this would inherit all own Objects and Properties of a and become own properties of b
this.d=d;
this.e=e;
}
a.doNotConstruct=true;
b.prototype=new a (); //--- this would only inherit the prototype, construct becomes false and isnt worked through, which if not would result in adding propertiy x and y to prototype instead of directly to instance of b,
a.doNotConstruct=false;
b.prototype.constructor=b;
var test=new b (1,2,3,4);
b.methoda ();
put this in a function
function prototypeInheritance (inheritor,parent)
{
parent.doNotConstruct=true;
inheritor=new parent ();
inheritor.prototype.constructor=inheritor;
inheritor.parent=parent;
parent.doNotConstruct=false;
}
you can call the parent property with (arguments.callee.parent) in the inheritor constructor and you can check doNotConstruct with arguments.callee.doNotConstruct in the parent constructor
According to Douglas Crockford I could use something like http://javascript.crockford.com/prototypal.html (with a little bit of tweaking)... but I am interested in jQuery way of doing it. Is it good practice using $.extend ?
I have 4 classes :
var A = function(){ }
A.prototype = {
name : "A",
cl : function(){
alert(this.name);
}
}
var D = function(){}
D.prototype = {
say : function(){
alert("D");
}
}
var B = function(){} //inherits from A
B.prototype = $.extend(new A(), {
name : "B"
});
var C = function(){} //inherits from B and D
C.prototype = $.extend(new B(), new D(), {
name : "C"
});
var o = new C();
alert((o instanceof B) && (o instanceof A) && (o instanceof C)); //is instance of A, B and C
alert(o instanceof D); //but is not instance of D
So, i can call every method, property ... from A, B, C and D. Problem comes, when I want to test if o is instance of D? How can I overcome this problem?
Is it good practice using $.extend
$.extend is useful for singletons but for prototypes is not ideal.
Using Object.create (or Crockford's polyfill) you can easily create classes like this. I'm using $.extend to simply process the properties and give them default values and the module pattern to keep it well organized. Hope this helps:
// Helper that makes inheritance work using 'Object.create'
Function.prototype.inherits = function(parent) {
this.prototype = Object.create(parent.prototype);
};
var Person = (function PersonClass() {
var _defaults = {
name: 'unnamed',
age: 0
};
function Person(props) {
$.extend(this, props, _defaults);
}
Person.prototype = {
say: function() {
return 'My name is '+ this.name;
}
};
return Person;
}());
var Student = (function StudentClass(_super) {
Student.inherits(_super); // inherit prototype
var _defaults = {
grade: 'untested'
};
function Student(props) {
_super.apply(this, arguments); // call parent class
$.extend(this, props, _defaults);
}
Student.prototype.say = function() {
return 'My grade is '+ this.grade;
};
return Student;
}(Person));
var james = new Student({ name: 'James', grade: 5 });
console.log(james instanceof Student); // true
console.log(james instanceof Person); // true
An object has only one prototype, so you cannot make it an instance of two other types with one call.
$.extend(new B(), new D(), ... creates an object that is an instance of B. Then all properties of D are copied to the newly created object. But the object will still be an instance of B.
Using $.extend is neither good nor bad per se. But you are bound to jQuery, which makes your code less reusable. And you have to be aware of the fact that $.extend overwrites properties with the same name, which might or might not be what you want.
I'm trying to override methods of an object but still call the prototype's original method using Object.getPrototypeOf(). This works great the first time, but if the method is overridden more than once there are problems.
This code results in a stack overflow:
A =
{
blurg: function()
{
puts('hey there')
}
}
B = (function buildB(){
var obj = Object.create(A)
obj.blurg = function()
{
Object.getPrototypeOf(this).blurg.apply(this, arguments)
puts('hai!!!!')
}
return obj
})()
b = (function buildb(){
var obj = Object.create(B)
obj.blurg = function()
{
Object.getPrototypeOf(this).blurg.apply(this, arguments)
puts('bye bye')
}
return obj
})()
b.blurg()
jsFiddle
The problem is that I want to call the prototype's method with the current object as this. This causes problems when that method does the same thing.
Am I going about this the wrong way? Is there a way I could create a helper function for making sure the correct prototype is pulled up? I'm a bit at a loss.
The problem is that in JavaScript, by nature, this always refers to the bottom down object instance in a prototype chain, so when you override methods in a hierarchical structure like above, this.prototype.someMethod() refers to the exact base class of the object instance, it doesn't seem to be a problem when you have maximum of two levels of hierarchy, however when you define three levels of hierarchical structure or more, recursion is inevitable! here's how:
A: grand super class
B: super class - inherits from A (B.prototype = A)
C: class - inherits from B (C.prototype = B)
a: instance of A (defines someMethod)
b: instance of B (defines someMethod, calls A.someMethod through Object.getPrototypeOf(this))
c: instance of C (defines someMethod, calls B.someMethod through Object.getPrototypeOf(this))
When b.someMethod is called, it can successfully call A's someMethod (Object.getPrototypeOf(this) returns A when called by b)
However when c.someMethod is called, it first calls b.someMethod, which in turn calls b.someMethod because Object.getPrototypeOf(this) always returns B when called by c! And here's where stack overflow occurs.
To resolve this, try to store a base class reference whenever you define a new sub-class, avoid using this when calling a super-class method:
A =
{
blurg: function () {
console.log('hey there')
}
};
B = (function buildB() {
var obj = Object.create(A);
var base = Object.getPrototypeOf(obj);
obj.blurg = function () {
base.blurg.apply(this, arguments);
console.log('hai!!!!')
}
return obj
})();
C = (function buildb() {
var obj = Object.create(B);
var base = Object.getPrototypeOf(obj);
obj.blurg = function () {
base.blurg.apply(this, arguments);
console.log('bye bye');
}
return obj
})();
C.blurg();
Scenario 1 - everything works:
var AwesomeObject = function()
{
var self = this;
self.whatstuff = 'really awesome';
}
AwesomeObject.prototype.doStuff = function()
{
var self = this;
console.log('i did '+self.whatstuff+' stuff');
return self;
}
var awesome = new AwesomeObject(); //returns a new AwesomeObject
awesome.doStuff(); // prints 'i did really awesome stuff' on the console
Now i want it even awesomer:
var AwesomeObject = function()
{
var f = function() { console.log('i am awesome'); }
var self = f;
self.whatstuff = 'really awesome';
return self;
}
AwesomeObject.prototype.doStuff = function()
{
var self = this;
console.log('i did '+self.whatstuff+' stuff');
return self;
}
var awesome = new AwesomeObject(); //returns the interal f object
awesome(); // prints 'i am awesome'
awesome.doStuff(); // throws an error
new AwesomeObject should return an executable function itself, so that i can say 'awesome();'
but i want it to inherit the AwesomeObject.prototype, too.
adding self.prototype = AwesomeObject.prototype; does not help.
var AwesomeObject = function()
{
var f = function() { console.log('i am awesome'); }
var self = f;
self.whatstuff = 'really awesome';
self.prototype = AwesomeObject.prototype;
return self;
}
ok i can copy the AwesomeObject.prototype functions - one after the other - into the scope of f
var AwesomeObject = function()
{
var f = function() { console.log('i am awesome'); }
var self = f;
self.whatstuff = 'really awesome';
self.doStuff = function() { AwesomeObject.prototype.doStuff.apply(self,arguments); }
return self;
}
but i think there must be a better way, a better pattern, what is it?
this issue drives me crazy, help would be really appreciated.
in general: how to create a function object that
can be created with new
returns a function object that can be executed
inherits all properties and methods of a given prototype
?
is there a way?
thx
Franz
A very simple pattern is a factory.
var AwesomeObject = (function() {
var AwesomeObject = function() {
this.whatstuff = 'really awesome';
};
AwesomeObject.prototype.doStuff = function() {
console.log('i did ' + this.whatstuff + ' stuff');
return this;
};
return function() {
var o = new AwesomeObject();
var f = function() { console.log("I am awesome"); };
for (var k in o) {
f[k] = o[k];
}
return f;
};
})();
var foo = AwesomeObject();
foo();
foo.doStuff();
Live Example.
The idea is that you seperate your function and your object into two things. Your object exists in the local scope of your function and the function can use the object.
The object itself inherits completely through the prototype.
The key is do forward all properties/methods of the object onto the function.
This is the cleanest solution.
When a property is resolved the prototype chain is traversed as you probably know.
But if you have an object awesome and try to evaluate awesome.doStuff, then awesome.prototype will never be queried for the property. You can verify this in your example, "doStuff" in awesome => false but "doStuff" in awesome.prototype => true.
So what you're doing is not changing the implicit properties of awesome, you are changing its prototype, meaning any objects created by doing new awesome will have that property. Verification: "doStuff" in new awesome() => true. And this makes sense, since there is no way to distinguish between a constructor or a regular function when using f/awesome.
The procedure when resolving a property p on an object o is roughly as follows:
Check whether p is defined on o
Check whether p is defined on o.__proto__ (usage of __proto__ is non-standard but widely implemented, except for jscript last time i checked and it has now been deprecated in SpiderMonkey)
Check whether p is defined on o.constructor.prototype
Check whether p is defined on o.constructor.prototype.prototype
etc
So one solution would be to simply set o.__proto__ = AwesomeClass.prototype. Think of __proto__ as a hidden intermediary object between an object and its prototype. Each instance receives its own unique __proto__ object. But this is deprecated and non-standard like I said.
We could also set the values in Function.prototype but that would override other Function properties and affect all Function instances. We don't want that.
So what's left? Not much it turns out. There is no way to set the complete prototype of an object while retaining it's inherited prototype. You will need to iterate through your prototype and copy all properties. Fortunately this will allow instanceof to behave as expected when working with chains of constructors, as well as allowing inheritance/overriding of properties properly.
The problem is really that there is no built-in way to copy the properties of an object into another one, and that there is no standard way to change an object's prototype chain ad-hoc (__proto__).
So use __proto__, or iterate through the prototype.
I don't think there is a good way to do this. I would redesign your program to avoid it.
However, here is a bad, platform-dependent solution (works on V8 using non-standard __proto__ property):
var PrototypeToBeInherited = {'inheritedProperty': 'inheritedPropertyValue'};
f = function() {
return "result";
};
f.__proto__ = PrototypeToBeInherited;
f()
=> "result";
f.inheritedProperty
=> "inheritedPropertyValue"
For your requirement that it must be created with "new", just wrap it in function:
F = function() {
return f;
}
var instance = new F();