class 浅析

ES6 规范中,引入了 class 的概念。
但是 JS 中并没有一个真正的 class 原始类型, class 仅仅只是对原型对象运用语法糖。
函数声明和类声明之间的一个重要区别在于, 函数声明会提升,类声明不会。

class Cat{
    constructor(name,age){
        this.name = name;
        this.age = age;
    }
	
    Say(){
        return '我的名字是' + this.name;
    }
}
var cat1 = new Cat('有鱼',2);
console.log(cat1.Say()); //我的名字是有鱼

cat1.constructor === Cat //true
cat1.__proto__ === Cat.prototype //true

class与原型的关系

class本质上就是一个函数,自身指向的就是构造函数

console.log(typeof Cat);// function
console.log(Cat.prototype.constructor === Cat);//true

image

class是构造函数的另一种写法,仍然存在prototype方法

console.log(Cat.prototype);//object

可以通过原型prototype修改类方法和新增方法

Cat.prototype.Say = function(){
    return '我的名字是' + this.name+',我是原型prototype声明同样的Say方法,把原有Say方法覆盖了';
}
cat2 = new Cat('年年',5);
console.log(cat2.Say());//我的名字是年年,我是原型prototype声明同样的Say方法,把原有Say方法覆盖了
Cat.prototype.Go = function(){
    return '我的年龄是' + this.age;
}
console.log(cat2.Go());//我的年龄是5

还可以通过Object.assign方法来为对象动态增加方法

Object.assign(Cat.prototype,{
    Eat:function(){
        return this.name;
    },
    Run:function(){
        return this.age;
    }
})
cat3 = new Cat('卡卡',4);
console.log(cat3.Eat());//卡卡
console.log(cat3.Run());//4

也可以使用实例对象的__proto__属性新增类的方法

cat3 = new Cat('卡卡',4);
cat4 = new Cat('楼楼',10);
cat3.__proto__.Play = function(){
    return this.name;
}
console.log(cat3.Play());// 卡卡
console.log(cat4.Play());// 楼楼
posted @ 2022-01-21 15:55  远方的少年🐬  阅读(43)  评论(0编辑  收藏  举报