ES6中的class的使用

发布时间:2019-08-09 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了ES6中的class的使用脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

js的传统生成一个类的方法,需要定义一个构造函数,然后通过new的方式生成。

function Cat() {
    this.name = 'kITty';
    this.color = 'yellow';
}
VAR cat = new Cat();

js中只有对象,没有类。这样的写法和传统面向对象语言差异很大,很容易让新手感到困惑


定义类

ES6添加了类,作为对象的模板。通过class来定义一个类:

//定义类
class Cat {
    constructor() {
        this.name = 'kitty';
        this.color = 'yellow';
    }
    //不需要加分号隔开,否则会报错,而且不用加上function关键字
    getnames() {
        console.LOG('name:' + this.name);
    }
}
//使用new操作符得到一个实力对象
let cat = new Cat()

其实ES6的类,完全可以看作构造函数的另一种写法。

class Cat {
    //...
}
tyPEof Cat // "function"
Cat === Cat.PRototype.constructor // true
//类的数据类型就是函数,类本身就只想构造函数

而且构造函数的prototype属性,在ES6的“类”上面继续存在。事实上,类的所有方法都定义在类的prototype属性上面

class Cat {
    constructor () {
        //...
    }
    like () {
        //...
    }
    eat(){
        //...
    }
}    
//等同于
Cat.prototype = {
    constructor () {},
    like () {},
    eat () {}
}

let miao = new Cat()
miao.constructor === Cat.prototype.constructor // true

严格模式

类和模块的内部,默认就是严格模式,所以不需要使用use strict指定运行模式。只要你的代码写在类或模块之中,就只有严格模式可用。
考虑到未来所有的代码,其实都是运行在模块之中,所以 ES6 实际上把整个语言升级到了严格模式。

constructor 方法

constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。


类的实例对象

用new命令生成类的实例对象

class Cat {
    //...
}
var cat = Cat ( 'kitty' , 'blue');//报错
var cat =  new Cat ( 'kitty' , 'blue'); //正确

实例的属性定义在原型上

//定义类
class Cat {
    constructor() {
        this.name = 'kitty';
        this.color = 'yellow';
    }
    getNames() {
        console.log('name:' + this.name);
    }
}
//使用new操作符得到一个实例对象
let cat = new Cat()
cat.getNames() // name:kitty
cat.hasOwnProperty('name')//true
cat.hasOwnProperty('getNames')//false
cat.__proto__.hasOwnProperty('getNames')//true

ES5一样,类的所有实例共享一个原型对象

let cat1 = new Cat();
let cat2 = new Cat();
cat1.__proto__ === cat2.__proto__

Class 表达式

let dogClass = class Dog {
    getclassname() {
        return Dog.name;
    }
}
let dog = new dogClass();
dog.getClassName() // Dog

不存在变量提升

定义类不存在变量提升,只能先定义类后使用,跟函数声明有区别的。

//-----函数声明-------
//定义前可以先使用,因为函数声明提升的缘故,调用合法。
func();
function func(){}

//-----定义类---------------
new Cat();  //报错,Cat is not defined
class Cat{}

this的指向

类的方法内部如果如果含有this,它默认指向类的实例。但是,必须非常小心,如果单独使用,有可能会报错。

class Cat {
    eatFish ( kind = 'fish'){
        this.print (`Hello ${fish}`);
    }
    print(str){
        console.log(str)
    }
}
let cat = new Cat();
const { eatFish } = cat;
eatFish;// TypeError: Cannot read property 'print' of undefined

上面代码中,eatFish方法中的this, 默认指向Cat类的实例。但是,如果将这个方法提取出来单独使用,this会指向该方法运行时所在的环境,因为找不到print() 方法而导致错误。

所以,可以在构造方法中绑定this,这样就不会找不到print方法了。

class Cat {
    constructor () {
        this.eatFish = this.eatFish.bind(this);
    }
    //...
}

或者使用箭头函数

class Cat {
    constructor () {
        this.eatFish = (kind = 'fish') => {
            this.print(`Hello ${name}`)
        }
    }
}

extends继承

使用extends 关键字实现类之间的继承。这比在ES5中使用继承要方便很多。

//定义类父类
class Parent {
    constructor(name,age){
        this.name = name;
        this.age = age;
    }

    speakSometing(){
        console.log("I can speek chinese");
    }
}
//定义子类,继承父类
class Child extends Parent {
    coding(){
        console.log("coding javascript");
    }
}

var c = new Child();

//可以调用父类的方法
c.speakSometing(); // I can speek chinese

如果子类中有constructor构造函数,则必须使用调用super

//定义父类
class Parent {
    constructor(name,age){
        this.name = name;
        this.age = age;
    }

    speakSometing(){
        console.log("I can speek chinese");
    }
}
//定义子类,继承父类
class Child extends Parent {
    constructor(name,age){
        //不调super(),则会报错  this is not defined

        //必须调用super
        super(name,age);
    }

    coding(){
        console.log("coding javascript");
    }
}

var c = new Child("job",30);

//可以调用父类的方法
c.speakSometing(); // I can speek chinese

子类必须在constructor方法中调用super方法,否则新建实例时会报错(this is not defined)。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。

参考:

http://es6.ruanyifeng.com/#docs/class
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes

脚本宝典总结

以上是脚本宝典为你收集整理的ES6中的class的使用全部内容,希望文章能够帮你解决ES6中的class的使用所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。