Question

Say that I have the generic clone implementation with C#:

public class Parent<T> where T : Parent, new()
{
    public T Clone()
    {
        return new T();
    }
}

public class Child : Parent<Child>{ }

This way, using new Child().Clone() will return an object of type Child instead of parent.

Is there an equivalent solution to javascript?

The most I can think of is using a function pointer like this:

var parent = function(){
};
parent.prototype.clonePointer = function(){ return new parent(); };
parent.prototype.clone = function(){
        return this.clonePointer();
    };

var child = function(){

};
child.prototype = Object.create(parent.prototype);
child.clonePointer = function(){ return new child(); };

Is there better solution than this?

Was it helpful?

Solution

If you set constructor back to its original value, i.e. Child, and establish inheritance properly:

function Child() {
    Parent.call(this);
}

Child.prototype = Object.create(Parent.prototype, {
    constructor: {value: Child}
});
// or, instead of passing a property descriptor
Child.prototype.constructor = Child;
// (but this makes `constructor` enumerable)

a clone method can be as simple as

Parent.prototype.clone = function() {
    return new this.constructor();
};

See also Classical inheritance with Object.create.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top