web前端全系列 教程
1839个小节阅读:2242.8k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
JavaScript 语言中,生成实例对象的传统方法是通过构造函数
xxxxxxxxxx
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(类)这个概念,作为对象的模板。通过class
关键字,可以定义类
基本上,ES6 的class
可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class
写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已
xxxxxxxxxx
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
constructor()
方法是类的默认方法,通过new
命令生成对象实例时,自动调用该方法。一个类必须有constructor()
方法,如果没有显式定义,一个空的constructor()
方法会被默认添加
xxxxxxxxxx
class Point {
}
// 等同于
class Point {
constructor() {}
}
生成类的实例的写法,与 ES5 完全一样,也是使用new
命令
xxxxxxxxxx
class Point {
// ...
}
// 报错
var point = Point(2, 3);
// 正确
var point = new Point(2, 3);
xxxxxxxxxx
class Person {
constructor(name) {
this.name = name;
}
get n() {
return this.name
}
set n(value) {
this.name = value;
}
}
var p = new Person("iwen")
console.log(p.n);
p.n = "ime"
console.log(p.n);
类和模块的内部,默认就是严格模式,所以不需要使用use strict
指定运行模式。只要你的代码写在类或模块之中,就只有严格模式可用。考虑到未来所有的代码,其实都是运行在模块之中,所以 ES6 实际上把整个语言升级到了严格模式
类不存在变量提升(hoist),这一点与 ES5 完全不同
xxxxxxxxxx
new Foo(); // ReferenceError
class Foo {}
由于本质上,ES6 的类只是 ES5 的构造函数的一层包装,所以函数的许多特性都被Class
继承,包括name
属性
xxxxxxxxxx
class Point {}
Point.name // "Point"
实时效果反馈
1. 下列代码,运行结果是什么:
xxxxxxxxxx
class Person {
constructor(name) {
this.name = name;
}
get n() {
return this.name
}
set n(value) {
this.name = value;
}
}
var p = new Person("sxt")
p.n = "itbaizhan"
console.log(p.n);
A sxt
B itbaizhan
C null
D undefined
答案
1=>B