示例 1
ES6Demo1.html 内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>ES Demo1 </title>
<!-- JQuery CDN-->
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<!-- H5 开始 script标签可以不用写 type 属性-->
<script src="ES6_Demo1.js"></script>
</head>
<body>
</body>
</html>
ES6Demo1.js 内容如下:
/**
* Created by Administrator on 2018/11/13 0013.
*/
$(function () {
//use strict:表示启用严格模式,严格模式下,代码书写必须符合规范,否则不通过
//从 ES5 开始,函数内部可以设定为严格模式;ES6开始 js 默认开启严格模式
'use strict';
/**
* Animal 相当与一个对象
* showName、showAge 是对象的方法
* @constructor
*/
var Animal = function () {
this.showName = function () {
console.log("My name is DogChen.\r\n");
}
this.showAge = function () {
console.log("我今年 8 岁.\r\n");
}
}
/**调用 Animal 对象的方法*/
new Animal().showName();
new Animal().showAge();
/**调用 Animal 对象的方法*/
var animal = new Animal();
animal.showName();
animal.showAge();
});
示例 2
ES6Demo1.html 内容不变,ES6Demo1.js 内容修改如下:
/**
* Animal 相当与一个对象
* showName、showAge 是对象的方法
* @constructor
*/
var Animal = function () {
/**
* 如果将来想要链式调用,则方法中将对象返回出去
* @returns {Animal}
*/
this.showName = function () {
console.log("My name is DogChen.\r\n");
return this;
}
this.showAge = function () {
console.log("我今年 8 岁.\r\n");
return this;
}
}
//除了直接在对象里面定义方法,也可以后期使用 prototype 关键字进行定义
Animal.prototype.showAddress = function () {
console.log("我家住在大明湖畔.\r\n");
return this;
}
$(function () {
//use strict:表示启用严格模式,严格模式下,代码书写必须符合规范,否则不通过
//从 ES5 开始,函数内部可以设定为严格模式;ES6开始 js 默认开启严格模式
'use strict';
/**调用 Animal 对象的方法*/
new Animal().showName().showAge().showAddress();
/**调用 Animal 对象的方法*/
var animal = new Animal();
animal.showName().showAge().showAddress();
});
示例 3
ES6Demo1.html 内容不变,ES6Demo1.js 内容修改如下:
//使用 class 关键字来定义类
class Animal {
//constructor 相当于类的构造器
constructor() {
console.log("Animal 无参构构造器执行...");
}
//constructor 相当于类的构造器,注意与 Java 可以重载构造器不同,ES 6 中类的构造器只能有一个
/*constructor(name, age) {
console.log("Animal 有参构造器执行,name=" + name + ",age=" + age);
}*/
}
$(function () {
new Animal();
//new Animal("华安", 35);
});
示例 4
ES6Demo1.html 内容不变,ES6Demo1.js 内容修改如下:
//使用 class 关键字来定义类
class Animal {
//constructor 相当于类的构造器
constructor() {
console.log("Animal 无参构构造器执行...");
}
//类中普通方法
showName() {
console.log("我叫金三顺.");
return this;
}
//类中的静态方法,类似 Java ,调用时直接使用 类.方法名,如 Animal.showAge()
// 这样调用 new Animal().showAge() 则是错误的
static showAge() {
console.log("静态方法,我今年 30 岁.");
return this;
}
}
$(function () {
new Animal().showName();
console.log("---------");
Animal.showAge();
});
扫描二维码关注公众号,回复:
4059874 查看本文章