有没有办法使用 OLOO 模式或工厂函数模式定义静态属性或方法?

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

下面是使用 OLOO 对象创建模式创建自行车对象的代码示例。

let bikePrototype = {
  init(make, model, brand) {
    this.make = make;
    this.model = model;
    this.brand = brand;
    return this;
  },

  info() {
    return `${this.brand} ::: ${this.model}`;
  }
};

let duke = Object.create(bikePrototype).init('Duke', '2020', 'KTM');
console.log(duke.info());
console.log(duke.__proto__.constructor === Object);
console.log(duke.__proto__.constructor.name === 'Object');
console.log(Object.getPrototypeOf(duke).constructor === Object);
console.log(Object.getPrototypeOf(duke).constructor.name === 'Object');
javascript object oop prototypal-inheritance
2个回答
0
投票

正如mdn所说

static 关键字定义类的静态方法或属性,或者 类静态初始化块(有关更多信息,请参阅链接 关于此用法)。

静态属性和方法被分配给类函数而不是类函数的原型。因此,我们不能使用类的实例调用静态方法和属性。但是,我们可以直接使用类名访问属性和方法。

所以让我展示一个使用

static
的示例及其使用的基本规则。

class Bike{
  static color = "green"; //static property 

  constructor(make, model, brand) {
    this.name = make ;
    this.model = model;
    this.brand = brand;
  }

  static printBike(bike){ // static method 
    console.log(`Name - ${bike.name } \nModel - ${bike.model} \nBrand - ${Bike.color}`);
  }
}

let bike = new Bike('Duke', '2020', 'KTM'); 

console.log("Accessing Bike.color static property"); 
console.log(Bike.color);

console.log("Calling static method Bike.printBike"); 
Bike.printBike(bike);

console.log(bike.color); // undefined because static property not available in instance 
console.log(bike.printBike); // undefined because static method not available in instance 

0
投票

是的。我只是在想,这没有意义,因为 OLOO 模式包括构建要为其创建实例的对象的实际原型。因为您拥有的只是实际的原型,所以您没有任何构造函数来添加属性。 (至少,这是我现在的想法)

© www.soinside.com 2019 - 2024. All rights reserved.