I started reading about inheritance in constructors (everything is clear in classes) and ran into some problems and misunderstandings. Could you explain to me which code practices are normal and which ones should be avoided?
1) Are these equivalent way to check whether object is instance of Parent?
let Parent = function(a){
this.a = a
}
let obj = new Parent()
console.log(obj.constructor === Parent ) // true
console.log(obj.__proto__ === Parent.prototype) // true
console.log(obj instanceof Parent) // true
console.log(Object.getPrototypeOf(obj) === Object.getPrototypeOf(obj) ) // true
2) Is there any difference between these two examples?
function Shape() {
this.checkedPoints = []
}
function Rectangle(a){
this.__proto__ = new Shape()
this.a = a;
}
let m = new Rectangle("first")
let n = new Rectangle("second")
m.checkedPoints.push(1)
n.checkedPoints.push(2);
console.log(m.checkedPoints) // Array [ 1 ]
console.log(n.checkedPoints) // Array [ 2 ]
and
function Shape() {
this.checkedPoints = [];
}
function Rectangle(a) {
Shape.apply(this);
this.a = a;
}
let m = new Rectangle("first");
let n = new Rectangle("second");
m.checkedPoints.push(1);
n.checkedPoints.push(2);
console.log(m.checkedPoints); // Array [ 1 ]
console.log(n.checkedPoints); // Array [ 2 ]
3) Why can't I access properties of Shape although m is instance of Shape????
function Shape() {
this.checkedPoints = [];
}
function Rectangle(a) {
this.a = a;
Object.setPrototypeOf(this.__proto__, Shape.prototype)
}
let m = new Rectangle("first");
console.log(m instanceof Shape, m instanceof Rectangle) // true true
console.log(m.a) //first
m.checkedPoints.push(1) // m.checkedPoints is undefined