广告位联系
返回顶部
分享到

原生JavaScript之es6中Class的用法

JavaScript 来源:互联网搜集 作者:秩名 发布时间:2020-02-23 18:59:43 人浏览
摘要

es6class写法 ? 1 2 3 4 5 6 7 8 9 class Point { constructor(x, y) { this .x = x; this .y = y; } toString() { return ( + this .x + , + this .y + ) ; } } es5写法 ? 1 2 3 4 5 6 7 8 function Point(x, y) { this .x = x; this .y = y; } Point.proto

es6class写法

?
1
2
3
4
5
6
7
8
9
class Point {
 constructor(x, y) {
  this.x = x;
  this.y = y;
 }
 toString() {
  return '(' + this.x + ', ' + this.y + ')';
 }
}

es5写法

?
1
2
3
4
5
6
7
8
function Point(x, y) {
 this.x = x;
 this.y = y;
}
Point.prototype.toString = function () {
 return '(' + this.x + ', ' + this.y + ')';
};
var p = new Point(1, 2);

对比一下

基本上,ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。上面的代码用 ES6 的class改写 就是第一个那样

上面代码定义了一个“类”,可以看到里面有一个constructor方法,这就是构造方法,而this关键字则代表实例对象。也就是说,ES5 的构造函数Point,对应 ES6 的Point类的构造方法。

Point类除了构造方法,还定义了一个toString方法。注意,定义“类”的方法的时候,前面不需要加上function这个关键字,直接把函数定义放进去了就可以了。另外,方法之间不需要逗号分隔,加了会报错。

使用的时候,也是直接对类使用new命令,跟构造函数的用法完全一致。

?
1
2
3
4
5
6
7
class Bar {
 doStuff() {
  console.log('stuff');
 }
}
var b = new Bar();
b.doStuff() // "stuff"

其实就是调用原型上的方法。

| `class B {}
let b = new B();

b.constructor === B.prototype.constructor // true`| |

上面代码中,b是B类的实例,它的constructor方法就是B类原型的constructor方法。

constructor 方法

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

?
1
2
3
4
5
6
class Point {
}
// 等同于
class Point {
 constructor() {}
}

上面代码中,定义了一个空的类Point,JavaScript 引擎会自动为它添加一个空的constructor方法。

constructor方法默认返回实例对象(即this),完全可以指定返回另外一个对象。

?
1
2
3
4
5
6
class Foo {
 constructor() {
  return Object.create(null);
 }
}
new Foo() instanceof Foo

静态方法

类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。

?
1
2
3
4
5
6
7
8
class Foo {
 static classMethod() {
  return 'hello';
 }
}
Foo.classMethod() // 'hello'
var foo = new Foo();
foo.classMethod()

注意,如果静态方法包含this关键字,这个this指的是类,而不是实例。
父类的静态方法,可以被子类继承

?
1
2
3
4
5
6
7
8
class Foo {
 static classMethod() {
  return 'hello';
 }
}
class Bar extends Foo {
}
Bar.classMethod() // 'hello'

上面代码中,父类Foo有一个静态方法,子类Bar可以调用这个方法。

静态方法也是可以从super对象上调用的。

?
1
2
3
4
5
6
7
8
9
10
11
class Foo {
 static classMethod() {
  return 'hello';
 }
}
class Bar extends Foo {
 static classMethod() {
  return super.classMethod() + ', too';
 }
}
Bar.classMethod() /


版权声明 : 本文内容来源于互联网或用户自行发布贡献,该文观点仅代表原作者本人。本站仅提供信息存储空间服务和不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权, 违法违规的内容, 请发送邮件至2530232025#qq.cn(#换@)举报,一经查实,本站将立刻删除。
原文链接 : https://blog.csdn.net/mlonly/article/details/87894187
相关文章
  • 本站所有内容来源于互联网或用户自行发布,本站仅提供信息存储空间服务,不拥有版权,不承担法律责任。如有侵犯您的权益,请您联系站长处理!
  • Copyright © 2017-2022 F11.CN All Rights Reserved. F11站长开发者网 版权所有 | 苏ICP备2022031554号-1 | 51LA统计