是否可以从 javascript 中的“构造函数”调用 class 方法?
Is it possible to call class methods from the `contructor` in javascript?
下面是一个ES6的例子Class。
class Car {
constructor(brand) {
this.brand = brand;
// this.setBrand(brand); // how is it possible to do this?
}
setBrand(brand) {
this.brand = brand;
}
getBrand() {
return this.brand;
}
getAd() {
return `${this.brand} is the best brand out there!!`;
}
}
但是,由于构造函数只是方法 setBrand
的重复,我想知道如何删除冗余并可能从 [=15= 中调用 setBrand
].
有什么指点吗?
猜猜就猜猜。在构造函数中 this
是对新对象的引用,因此您可以在其中调用 class 方法。下面的代码运行正常。
class Car {
constructor(brand) {
this.setBrand(brand); // this works fine
}
setBrand(brand) {
this.brand = brand;
}
getBrand() {
return this.brand;
}
getAd() {
return `${this.brand} is the best brand out there!!`;
}
}
let car = new Car("DeLorean")
console.log(car.getBrand())
console.log(car.getAd())
您可以通过以下方式调用该方法:
class Car {
constructor(brand) {
this.setBrand(brand); <--------
}
setBrand(brand) {
this.brand = brand;
}
}
在这种情况下没问题,因为您只是为 属性 赋值,但请记住,让构造函数执行创建对象以外的任何操作都是不好的做法。
下面是一个ES6的例子Class。
class Car {
constructor(brand) {
this.brand = brand;
// this.setBrand(brand); // how is it possible to do this?
}
setBrand(brand) {
this.brand = brand;
}
getBrand() {
return this.brand;
}
getAd() {
return `${this.brand} is the best brand out there!!`;
}
}
但是,由于构造函数只是方法 setBrand
的重复,我想知道如何删除冗余并可能从 [=15= 中调用 setBrand
].
有什么指点吗?
猜猜就猜猜。在构造函数中 this
是对新对象的引用,因此您可以在其中调用 class 方法。下面的代码运行正常。
class Car {
constructor(brand) {
this.setBrand(brand); // this works fine
}
setBrand(brand) {
this.brand = brand;
}
getBrand() {
return this.brand;
}
getAd() {
return `${this.brand} is the best brand out there!!`;
}
}
let car = new Car("DeLorean")
console.log(car.getBrand())
console.log(car.getAd())
您可以通过以下方式调用该方法:
class Car {
constructor(brand) {
this.setBrand(brand); <--------
}
setBrand(brand) {
this.brand = brand;
}
}
在这种情况下没问题,因为您只是为 属性 赋值,但请记住,让构造函数执行创建对象以外的任何操作都是不好的做法。