这篇文章主要介绍es6中类的示例,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
类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实例的原型
在我看来
constructor() {
this.a = 1;
this.b = this.f;
}
这部分相当于es5中构造函数的作用,在new的过程中对this进行赋值,并返回this也就成了实例对象
因此你在constructor中return了一个对象且不等于null那么实例对象就是return的值,和es5构造函数一样的效果
f() {
return this;
}
这个方法最终属于在实例对象的原型链上不可遍历方法,因此也能被实例对象使用
表示该方法不会被实例继承,而是直接通过类来调用
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 内部只有静态方法,没有静态属性
var o = new class {
constructor(n) {
this.a = n;
this.b = this.f;
}
g() {
return n;
}
f() {
return this;
}
}(1)
o.a; // 1
class类声明不存在变量提升
是在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中类的示例”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。