class继承

ES6中引入class创建类,extends实现类的继承,通过new来创建实例类,这种形式的类的创建与继承与Java等面向对象编程语言更为相似

class Point{
    constructor(x,y){ // -- 每个类都要有constructor,若没有显式定义,则会默认添加空的constructor
        this.x = x
        this.y = y
    }
    toString (){
        return '('+this.x+','+this.y+')'
    }    
}
var p1 = new Point(1,2)
console.log(p1.toString()) //(1,2)

类的所有方法都是定义在prototype对象上的,可以通过Object.assign来给类添加属性方法,或者通过Object.getPrototypeof(obj),或者obj.__proto__来添加

Object.assign(Point.prototype,{ // 给类添加方法1
    toValue(){
        return Math.sqrt(this.x*this.x+this.y*this.y).toFixed(2)
    }
})
Object.getPrototypeOf(p1).toValue = function(){ // 给类添加方法2
    return Math.sqrt(this.x*this.x+this.y*this.y).toFixed(2)
}
p1.__proto__.toValue = function(){ 给类添加方法3
    return Math.sqrt(this.x*this.x+this.y*this.y).toFixed(2)
}
console.log("toValue",p1.toValue()) // 2.24

在类中,可以定义静态方法,在方法名前面加上static,不会被实例继承,调用时通过类来调用,不能通过实例来调用,父类中的静态方法会被子类继承

class Point{  
    static staticFunc(){
        console.log("this is a static function")
    } 
}
class ColorPoint extends Point{

}
var p1 = new Point()
Point.staticFunc() //this is a static function
ColorPoint.staticFunc() //this is a static function
p1.staticFunc() //TypeError: p1.staticFunc is not a function

es6中通过extends来实现类的继承子类的构造函数必须执行一次super,在执行super之前,不可以使用thissuper代表父类的构造函数,返回的是子类的实例,相当与A.prototype.constructor.call(this)

es5和es6的类的继承机制是不同的,es5是先创建子类实例对象this,然后再将父类上的方法添加到this上,es6则是通过现将父类方法添加到this上,然后再通过子类constructor改变this

class ColorPoint extends Point {
    constructor(x,y,color){
        super(x,y) 
        this.color = color
    }
    toString(){
        return this.color+" "+super.toString()
    }
}
var cp = new ColorPoint(2,3,'red') // 通过new来创建实例
console.log(cp instanceof ColorPoint) // true
console.log(cp instanceof Point) // true
console.log(Object.getPrototypeOf(ColorPoint) === Point) // true -- 用该方法来判断一个类是否继承另一个类


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值