今天我学会了 JS 的构造函数的推荐写法,代码如下:
function Person(name = 'Jonny', age = 0) {
this.name = name
this.age = age
}
Person.prototype = {
constructor : Person,
sayName() {
console.log('Hi, I am ${this.name}')
},
sayAge() {
console.log('I am ${this.age} years old')
}
}
const f1 = new Person('fang', 18)
f1.sayName()
f1.sayAge()
除了上面这种构造函数写法,我们还可以使用 class 写法,代码如下:
class Person{
constructor (name = 'Tony', age = 0) {
this.name = name
this.age = age
}
sayName() {
console.log('Hello, I am ${this.name}')
}
sayAge() {
console.log('Hello, I am ${this.age} years old')
}
}