下面是使用 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');
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
是的。我只是在想,这没有意义,因为 OLOO 模式包括构建要为其创建实例的对象的实际原型。因为您拥有的只是实际的原型,所以您没有任何构造函数来添加属性。 (至少,这是我现在的想法)