构造函数继承问题

问题描述 投票:0回答:0

我开始阅读构造函数中的继承(类中的一切都很清楚)并遇到了一些问题和误解。你能给我解释一下哪些代码实践是正常的,哪些应该避免吗?

1)这些是检查对象是否是父实例的等效方法吗?

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)这两个例子有什么区别吗?

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 ]

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)为什么我不能访问 Shape 的属性,尽管 m 是 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
javascript inheritance constructor prototypejs prototype-chain
© www.soinside.com 2019 - 2024. All rights reserved.