上面的章节中我们看到了JavaScript的对象模型是基于原型实现的,特点是简单,缺点是理解起来比传统的类-实例模型要困难,最大的缺点是继承的实现需要编写大量代码,并且需要正确实现原型链。
有没有更简单的写法?有!
新的关键字class从ES6开始正式被引入到JavaScript中。class的目的就是让定义类更简单。
我们先回顾用函数实现Student的方法:
function Student(name) { this.name = name; } Student.prototype.hello = function () { alert('Hello, ' + this.name + '!'); }
如果用新的class关键字来编写Student,可以这样写:
class Student { constructor(name) { this.name = name; } hello() { alert('Hello, ' + this.name + '!'); } }
比较一下就可以发现,class的定义包含了构造函数constructor和定义在原型对象上的函数hello()(注意没有function关键字),这样就避免了Student.prototype.hello = function () {...}这样分散的代码。
最后,创建一个Student对象代码和前面章节完全一样:
var xiaoming = new Student('小明'); xiaoming.hello();
用class定义对象的另一个巨大的好处是继承更方便了。想一想我们从Student派生一个PrimaryStudent需要编写的代码量。现在,原型继承的中间对象,原型对象的构造函数等等都不需要考虑了,直接通过extends来实现:
class PrimaryStudent extends Student { constructor(name, grade) { super(name); // 记得用super调用父类的构造方法! this.grade = grade; } myGrade() { alert('I am at grade ' + this.grade); } }
注意PrimaryStudent的定义也是class关键字实现的,而extends则表示原型链对象来自Student。子类的构造函数可能会与父类不太相同,例如,PrimaryStudent需要name和grade两个参数,并且需要通过super(name)来调用父类的构造函数,否则父类的name属性无法正常初始化。
PrimaryStudent已经自动获得了父类Student的hello方法,我们又在子类中定义了新的myGrade方法。
ES6引入的class和原有的JavaScript原型继承有什么区别呢?实际上它们没有任何区别,class的作用就是让JavaScript引擎去实现原来需要我们自己编写的原型链代码。简而言之,用class的好处就是极大地简化了原型链代码。
你一定会问,class这么好用,能不能现在就用上?
现在用还早了点,因为不是所有的主流浏览器都支持ES6的class。如果一定要现在就用上,就需要一个工具把class代码转换为传统的prototype代码,可以试试Babel这个工具。
需要浏览器支持ES6的class,如果遇到SyntaxError,则说明浏览器不支持class语法,请换一个最新的浏览器试试。
类是用于创建对象的模板。JavaScript中生成对象实例的方法是通过构造函数,这跟主流面向对象语言(java,C#)写法上差异较大,如下:
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')';
};
var p = new Point(1, 1);
ES6 提供了更接近Java语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。
如下:constructor()是构造方法,而this代表实例对象:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
类的数据类型就是函数,它本身就是指向函数的构造函数:
// ES5 函数声明
function Point() {
//...
}
// ES6 类声明
class Point {
//....
constructor() {
}
}
typeof Point // "function"
Point === Point.prototype.constructor // true
在类里面定义的方法是挂到Point.prototype,所以类只是提供了语法糖,本质还是原型链调用。
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
Point.prototype = {
//....
toString()
}
var p = new Point(1, 1);
p.toString() // (1,1)
类的另一种定义方式类表达式
// 未命名/匿名类
let Point = class {
constructor(x, y) {
this.x = x;
this.y = y;
}
};
Point.name // Point
函数声明和类声明有个重要区别,函数声明会提升,类声明不会提升。
constructor()方法是类的默认方法,new生成实例对象时会自动调用该方法。
一个类必须有constructor()方法,如果没有显式定义,引擎会默认添加一个空的constructor()。
constructor()方法默认返回实例对象(即this)。
class Point {
}
// 自动添加
class Point {
constructor() {}
}
与 ES5 一样,在类的内部可以使用get和set关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为。
class User {
constructor(name) {
this.name = name;
}
get name() {
return this.name;
}
set name(value) {
this.name = value;
}
}
类的方法内部的this,它默认指向类的实例,在调用存在this的方法时,需要使用 obj.method()方式,否则会报错。
class User {
constructor(name) {
this.name = name;
}
printName(){
console.log('Name is ' + this.name)
}
}
const user = new User('jack')
user.printName() // Name is jack
const { printName } = user;
printName() // 报错 Cannot read properties of undefined (reading 'name')
如果要单独调用又不报错,一种方法可以在构造方法里调用bind(this)。
class User {
constructor(name) {
this.name = name;
this.printName = this.printName.bind(this);
}
printName(){
console.log('Name is ' + this.name)
}
}
const user = new User('jack')
const { printName } = user;
printName() // Name is jack
bind(this) 会创建一个新函数,并将传入的this作为该函数在调用时上下文指向。
另外可以使用箭头函数,因为箭头函数内部的this总是指向定义时所在的对象。
class User {
constructor(name) {
this.name = name;
}
printName = () => {
console.log('Name is ' + this.name)
}
}
const user = new User('jack')
const { printName } = user;
printName() // Name is jack
静态属性指的是类本身的属性,而不是定义在实例对象this上的属性。
class User {
}
User.prop = 1;
User.prop // 1
可以在类里面定义静态方法,该方法不会被对象实例继承,而是直接通过类来调用。
静态方法里使用this是指向类。
class Utils {
static printInfo() {
this.info();
}
static info() {
console.log('hello');
}
}
Utils.printInfo() // hello
关于方法的调用范围限制,比如:私有公有,ES6暂时没有提供,一般是通过约定,比如:在方法前面加下划线_print()表示私有方法。
Java中通过extends实现类的继承。ES6中类也可以通过extends实现继承。
继承时,子类必须在constructor方法中调用super方法,否则新建实例时会报错。
class Point3D extends Point {
constructor(x, y, z) {
super(x, y); // 调用父类的constructor(x, y)
this.z = z;
}
toString() {
return super.toString() + ' ' + this.z ; // 调用父类的toString()
}
}
父类的静态方法,也会被子类继承。
class Parent {
static info() {
console.log('hello world');
}
}
class Child extends Parent {
}
Child.info() // hello world
在子类的构造函数必须执行一次super函数,它代表了父类的构造函数。
class Parent {}
class Child extends Parent {
constructor() {
super();
}
}
在子类普通方法中通过super调用父类的方法时,方法内部的this指向当前的子类实例。
class Parent {
constructor() {
this.x = 1;
this.y = 10
}
printParent() {
console.log(this.y);
}
print() {
console.log(this.x);
}
}
class Child extends Parent {
constructor() {
super();
this.x = 2;
}
m() {
super.print();
}
}
let c = new Child();
c.printParent() // 10
c.m() // 2
初学JavaScript时,_proto_和prototype 很容易混淆。首先我们知道每个JS对象都会对应一个原型对象,并从原型对象继承属性和方法。
下图是一些拥有prototype内置对象。
prototype
根据上面描述,看下面代码
var obj = {} // 等同于 var obj = new Object()
// obj.__proto__指向Object构造函数的prototype
obj.__proto__ === Object.prototype // true
// obj.toString 调用方法从Object.prototype继承
obj.toString === obj.__proto__.toString // true
// 数组
var arr = []
arr.__proto__ === Array.prototype // true
对于function对象,声明的每个function同时拥有prototype和__proto__属性,创建的对象属性__proto__指向函数prototype,函数的__proto__又指向内置函数对象(Function)的prototype。
function Foo(){}
var f = new Foo();
f.__proto__ === Foo.prototype // true
Foo.__proto__ === Function.prototype // true
类作为构造函数的语法糖,也会同时有prototype属性和__proto__属性,因此同时存在两条继承链。
class Parent {
}
class Child extends Parent {
}
Child.__proto__ === Parent // true
Child.prototype.__proto__ === Parent.prototype // true
子类实例的__proto__属性,指向子类构造方法的prototype。
子类实例的__proto__属性的__proto__属性,指向父类实例的__proto__属性。也就是说,子类的原型的原型,是父类的原型。
class Parent {
}
class Child extends Parent {
}
var p = new Parent();
var c = new Child();
c.__proto__ === p.__proto__ // false
c.__proto__ === Child.prototype // true
c.__proto__.__proto__ === p.__proto__ // true
JavaScript中的Class更多的还是语法糖,本质上绕不开原型链。欢迎大家留言交流。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
/*总体的样式*/
<style>
/*盒子样式*/
#box{
width: 350px; //宽
height: 450px; //高
border: 1px solid black; //边框
border-radius: 10px; //边框弧度
font-family: 黑体; //字体
letter-spacing:8px; //段间距
word-spacing: 10px; //字间距
line-height: 40px; //行高
font-size: 18px; //字大小
padding: 20px; //内边框
}
/*给'注册'赋予样式*/
.register{
width:280px ; //宽
height: 50px; //高
background-color: skyblue; //背景颜色
border-radius: 10px; //边框弧度
}
/*将所有边框都改变*/
*{
border-radius: 5px; 边框弧度
}
/*使用class选择器,赋予number宽高和边框*/
.number{
width: 185px; //宽
height: 27px; //高
border-width: 1px; //边框宽度
}
/*id选择器*/
#two{
width: 55px; //宽
border-width: 1px; 边框宽度
}
/*id选择器*/
#phone{
width: 103px; //宽
}
/*class 选择器*/
.boxs{
zoom: 75%; //清除浮动
color: darkgray; //颜色
}
/*class选择器*/
.box_a{
width: 50px; //宽
height: 50px; //高
background-image: url("../image/04.jpg "); //背景图片
background-repeat: no-repeat; // 是否平铺
background-size: 50px 25px; //背景尺寸
position: relative; //定位 相对定位
left: 310px; //定位后左移
bottom: 32px; //定位后下移
}
</style>
</head>
<body>
<div id="box">
<h1>请注册</h1>
<p style="color: darkgray">已有帐号?<a href="https://im.qq.com/index">登录</a></p>
<form action="" method="post">
<label for="name">用户名</label>
<input type="text" placeholder="请输入用户名" id="name" class="number"> <br>
<label for="phone">手机号</label>
<select name="" id="two" class="number">
<optgroup>
<option style="" class="">+86</option>
</optgroup>
</select>
<input type="text" placeholder="请输入手机号" id="phone" class="number"> <br>
<label for="mima">密 码</label>
<input type="password" placeholder="请输入密码" id="mima" class="number"> <br>
<label for="mima">验证码</label>
<input type="password" placeholder="请输入验证码" id="is" class="number">
<div class="box_a"></div>
<div class="boxs">
<input type="radio" id="" class="accept">阅读并接受协议<br>
</div>
<input type="submit" value="注册" class="register" >
</form>
</div>
</body>
</html>
在这里插入图片描述
*请认真填写需求信息,我们会在24小时内与您取得联系。