新旧用法
ES5:
function Person(name, age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
return this.name
}
ES6:
class Person{
//实例化的时候会立即调用
constructor(name, age){
this.name = name;
this.age = age;
} //后面没有逗号,因为这是方法
sayName(){
return this.name
}//后面没有逗号,因为这是方法
sayAge(){
return this,age
}//后面没有逗号,因为这是方法
}
或者:
class Person{
//实例化的时候会立即调用
constructor(name, age){
this.name = name;
this.age = age;
} //后面没有逗号,因为这是方法
Object.assign(Person.prototype, {
sayName(){
return this.name
},
sayAge(){
return this,age
},
})
}
1.匿名类
let Example = class {
constructor(a) {
this.a = a;
}
}
2.命名类
let Example = class Example {
constructor(a) {
this.a = a;
}
}
不可重复声明。
类定义不会被提升,这意味着,必须在访问前对类进行定义,否则就会报错。
类中方法不需要· function
关键字。
3.constructor 方法
constructor
方法是类的默认方法,创建类的实例化对象时被调用。
class Example{
constructor(){
console.log('我是constructor');
}
}
new Example(); // 我是constructor
4.原型方法,静态方法,实例方法
4.1静态方法
class Example{
static sum(a, b) {
console.log(a+b);
}
}
Example.sum(1, 2); // 3
4.2原型方法
class Example {
sum(a, b) {
console.log(a + b);
}
}
let exam = new Example();
exam.sum(1, 2); // 3
4.3实例方法
class Example {
constructor() {
this.sum = (a, b) => {
console.log(a + b);
}
}
}
5实例化
·class
的实例化必须通过 new
关键字。
6.继承
class Person{
//实例化的时候会立即调用
constructor(name, age){
this.name = name;
this.age = age;
} //后面没有逗号,因为这是方法
sayName(){
return this.name
}//后面没有逗号,因为这是方法
sayAge(){
return this,age
}//后面没有逗号,因为这是方法
}
class child entends Person{
constructor(name,age, length){
super(name, age); //相当于Person.call(this, name, age)
this.height = height;
}
}
1重写父类方法
class Person{
//实例化的时候会立即调用
constructor(name, age){
this.name = name;
this.age = age;
} //后面没有逗号,因为这是方法
sayName(){
return this.name
}//后面没有逗号,因为这是方法
sayAge(){
return this,age
}//后面没有逗号,因为这是方法
}
class child entends Person{
constructor(name,age, length){
super(name, age); //相当于Person.call(this, name, age)
this.height = height;
}
//重写父类方法
sayName(){
return super.name + super.age
}
}