Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

一个对象的属性也是一个对象,怎么进行解耦?

class Wheel{
  constructor(num) {
   this.num = num;
  }
  num:0,
  roll(){
   console.log('wheel is rolling!');
  }
}

class Car{
    constructor(engine, wheel) {
        this.engine = engine;
        this.wheel = wheel;
    }
    engine:0,
    wheel,
}

let wheel = new Wheel(4);
let car = new Car(1, wheel);
car.wheel.roll();

wheel对象是car对象的属性,怎么对car和wheel进行解耦,有时候属性对象的属性又是父对象,例如为wheel添加belong属性,表示所属的car,请问一般怎么进行解耦?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

我觉得现在就挺好的,至少没有将Wheel的参数传递给Car构造函数然后在构造函数内实例化。
进一步的,你可以在Wheel类添加方法setCar:

class Wheel{
  constructor(num) {
   this.num = num;
   this.car = null;
  }
  roll(){
   console.log('wheel is rolling!');
  }
  setCar (car) {
    this.car = car
  }
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...