这篇文章主要介绍es6中类的示例,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

成都创新互联公司于2013年创立,先为新和等服务建站,新和等地企业,进行企业商务咨询服务。为新和企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
类class
基本概念,记录以便自己后面加深理解
了解类是什么
class是什么?不妨写一个看看
class Demo {
constructor() {
this.a = 1;
this.b = this.f;
}
f() {
return this;
}
}
Demo.prototype; //{
// constructor: class Demo
// f: ƒ f()
// __proto__: Object }Demo的原型可以看到这三个属性都是不可遍历的并且与Demo类相比就多了一个__proto__原型链。我们再new一个Demo看一下
let o = new Demo();
console.log(Object.getPrototypeOf(o)); //{
// constructor: class Demo
// f: ƒ f()
// __proto__: Object }实际上Demo类相当于Demo实例的原型
class中的constructor
在我看来
constructor() {
this.a = 1;
this.b = this.f;
}这部分相当于es5中构造函数的作用,在new的过程中对this进行赋值,并返回this也就成了实例对象
因此你在constructor中return了一个对象且不等于null那么实例对象就是return的值,和es5构造函数一样的效果
class中的方法
f() {
return this;
}这个方法最终属于在实例对象的原型链上不可遍历方法,因此也能被实例对象使用
新知识点
class的静态方法
表示该方法不会被实例继承,而是直接通过类来调用
class Demo {
constructor() {
this.a = this;
this.b = this.f;
}
static g() {
return this;
}
static f() {
return this;
}
}
let o = new Demo();
//console.log(o.b()); //not a function
//console.log(o.g()); //not a function
Demo.g() === Demo; //true静态方法中的this指向类自己,而this.a = this则指向实例对象自己
静态方法可以被子类继承
class Foo {
static classMethod() {
return 'hello';
}
}
class Bar extends Foo {
}
Bar.classMethod() // 'hello'静态方法可以从super对象上调用
class Foo {
static classMethod() {
return 'hello';
}
}
class Bar extends Foo {
static classMethod() {
return super.classMethod() + ', too';
}
}
Bar.classMethod() // "hello, too"Class 内部只有静态方法,没有静态属性
class表达式的立即执行写法
var o = new class {
constructor(n) {
this.a = n;
this.b = this.f;
}
g() {
return n;
}
f() {
return this;
}
}(1)
o.a; // 1class类声明不存在变量提升
new.target 属性
是在new后返回一个对象,例如es5中构造函数f不是通过new调用返回undefined,通过new调用返回构造函数自己
function f() {
return new.target;
}
console.log((new f()) === f); //true而class类中,则返回class自身。和静态方法中this是一样的;new得是哪个类就返回哪个类
class Shape {
constructor() {
if (new.target === Shape) {
throw new Error('本类不能实例化');
}
}
}
class Rectangle extends Shape {
constructor(length, width) {
super();
// ...
}
}
var x = new Shape(); // 报错
var y = new Rectangle(3, 4); // 正确以上是“es6中类的示例”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!
本文题目:es6中类的示例
转载来于:http://www.jxjierui.cn/article/pooigs.html


咨询
建站咨询
