Proto Inheritance From Es6 Class
Solution 1:
Since you're running this all on an environment that actually supports real ES6 classes, you may be able to achieve what you're looking for. What you'll need to do is to change your subclass logic to be
varProtoChildFromClassParent = function(a) {
const _this = Reflect.construct(ClassParent, [a], new.target);
return _this;
}
Object.setPrototypeOf(ProtoChildFromClassParent, ClassParent);
Object.setPrototypeOf(ProtoChildFromClassParent.prototype, ClassParent.prototype);
This is predicated on Reflect.construct
being available, so it will not work on an older ES5 environment, but then neither would ES6 class syntax either. It's also important that new.target
be available. As long as both are available, this is very close to replicating the behavior you'd get from using actual class syntax. That said, immediately the question would be why you're not just doing
classProtoChildFromClassParentextendsClassParent {}
so whether this is useful or not really depends on what's stopping you from doing that to begin with.
Solution 2:
I was also interested on how to inherit in prototypical way from ES6 class, just to understand more in JS and here what I can propose:
classParent {
constructor(data){
this.#setPrivateProperty(data);
}
#privateProperty = "Parent private property";
#setPrivateProperty = (data)=>{
this.#privateProperty = data;
}
parentPublicMethod = ()=>{
console.log("Parent public method responded:", this.#privateProperty);
}
}
functionChild(data, parentData){
this.__proto__ = newParent(parentData)
this.childPublicProperty = data;
}
Child.prototype = Parent.prototype;
Child.prototype.constructor = Child;
let c = newChild("Child data", "Parent data");
// Output: "Parent public method responded: Parent data"
c.parentPublicMethod();
// Output: "Child public property value is: Child data"console.log("Child public property value is:", c.childPublicProperty);
// Output: "1. Instance of Child: true 2. Instance of Parent: true"console.log("1. Instance of Child:", c instanceofChild, "2. Instance of Parent:", c instanceofParent);
I will be very grateful to those people, who will criticize this code sample and maybe we get some more details. Thanks to All in advance!!!
Solution 3:
class
is just a friendlier syntax for older constructor function patterns.
i.e.:
const x = function () {};
const y = newx();
Is the same as:
classx {
constructor () {}
}
const y = newx();
y.prototype
refers to the constructor method of the x
class.
Post a Comment for "Proto Inheritance From Es6 Class"