ES6中的class的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36422236/article/details/82871479

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

猜你喜欢

转载自blog.csdn.net/sinat_36422236/article/details/82871479