1.传统方式定义类
function Point1(x,y){
this.x = x
this.y = y
}
Point1.prototype.add = function(){
return this.x + this.y
}
var p1 = new Point1(3,9)
console.log(p1.add())
2.class方式定义一个类
class Point2{
constructor(x, y){
this.x = x
this.y = y
}
add(){ // 这里的add方法实际上是定义在原型上的。
return this.x + this.y
}
}
var p2 = new Point2(4,77)
console.log(p2.add())
3.类的数据类型就是函数,类本身就是指向函数的,类的所有方法都是定义在类的prototype上的
class Point3{
say(){
//
}
eat(){
//
}
}
// 等同于以下
Point3.prototype.say = function(){
//
}
Point3.prototype.eat = function(){
//
}
// 等同于:
Point3.prototype = {
say(){},
eat(){},
}
所以:在类上调用方法,实际上是在原型上调用方法。
4.constructor方法
constructor方法是类的默认方法。new生成实例时,会默认调用constructor方法
一个类必须有constructor方法,如果没有显式的声明,就会自动创建一个空的constructor方法
class Con{
}
// 等同于
class Con{
constructor(){
//
}
}
// JavaScript引擎会自动给Con类添加一个constructor方法, 这个方法默认会返回实例对象(this)
5.类的静态方法
类是实例的原型,所有类的方法都会被实例继承。但是,如果在一个方法前面加上static关键字,就代表这是一个静态方法,这个静态方法不会被实例继承,而是通过类直接调用
静态方法可以与非静态方法可以重名
6.Class继承
class的继承是通过extends关键字实现的 基本语法-------class Dog extends Animal{}
这里的Cat类,通过extends关键字,继承了Animal类所有的属性和方法,因为没有代码,所以相当于复制了一份
class Animal{
constructor(name, age){
this.name = name
this.age = age
}
sayName(){
return "it's name is " + this.name
}
}
class Cat extends Animal{
constructor(name, age, color){
super(name, age) // super关键字调用父元素的方法
this.color = color
}
sayColor(){
return "the color is " + this.color
}
}
var bosimiao = new Cat("bosi", 2, 'yellow')
console.log(bosimiao.sayName()) // it's name is bosi
console.log(bosimiao.sayColor()) // the color is yellow
关于super关键字:
1、在子构造函数中,必须用super方法,否则新建对象的时候会报错
2、子构造函数中,使用this前必须先用super,否则会报错
ES6的继承机制:先创建父类的实例对象,再创建子类的实例,然后修改父类的this
7.Class原型链的方式继承
我们每创建一个函数,都有一个prototype属性(自带的),这个prototype属性是一个指针,指向了一个对象,这个对象是原型对象。
这个原型对象上有一个constructor属性。这个constructor属性是一个指针,指向了构造函数。
构造函数的new出来的实例对象,有一个__proto__属性(内部属性),这个属性指向原型对象。
所以实例也能访问原型对象的属性和方法。
原型对象通过constructor指针指向了构造函数
所有的构造函数也是Function的实例
所有构造函数的原型对象是Object的实例
所以,实例,构造函数,原型对象的关系是:
[].__proto__ === Array.prototype === 原型对象
[].__proto__.constructor === Array
Animal.prototype.constructor === Animal
prototype:每个函数都有显式原型prototype
__proto__:每个对象实例都有隐式原型__proto__
constructor:构造函数的原型有一个constructor属性,指向创建该对象的构造函数