Class语法
1.基本写法
2.get和set
3.静态
一、基本语法
在学习class之前,我们先回顾一下JS在Class之前对于类的应用,一般是使用构造函数来实现。
function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.say = function(){
console.log(this.name,this.age)
}
let obj = new Person("kerwin",100)
console.log(obj)
接着我们来看Class怎么写
class Person {
constructor(name, age) {
this.name = name
this.age = age
}
say() {
console.log(this.name, this.age)
}
}
let obj = new Person("kerwin", 100)
console.log(obj)
这里的效果跟传统写法的结果一模一样,constructor写入之前函数写入的内容。Person.prototype.say这种在原型上挂载的写法直接变成在class的定义里去写。本质上Class就是构造函数的语法糖。
二、get和set
和Proxy类似,class一样有get和set,一个是访问触发,一个是修改触发。
class Person {
constructor(name, age,location) {
this.name = name
this.age = age
this.location = location
}
get location(){
console.log("get")
}
set location(data){
console.log("set",data)
}
}
let obj = new Person("kerwin", 100,"dazhou")
console.log(obj)
值得一提的是,如果你想在这里让get打印location的值,直接return this.location一定会触发递归,从而让游览器崩溃,set同理。如何让get、set访问属性呢,下面是一个简单的例子。
<ul id="list">
</ul>
<script>
class Person {
constructor(name, age, id) {
this.name = name
this.age = age
this.ele = document.querySelector(`#${id}`)
}
get html() {
return this.ele.innerHTML
}
set html(data) {
this.ele.innerHTML = data.map(item => `<li>${item}</li>`).join("")
}
}
let obj = new Person("kerwin", 100, "list")
三、静态
像下面这样属于Person类自己的属性和方法,实例无法继承的叫做静态属性和方法。
class Person {
constructor(name, age) {
this.name = name
this.age = age
}
say() {
console.log(this.name, this.age)
}
}
Person.myname = "Person类的名字"
Person.mymethod = function(){
console.log("类的方法")
}
let obj = new Person("kerwin", 100)
console.log(obj)
当然在es6中有着更为简单的写法,使用static关键字可以更便捷的定义静态属性和方法
class Person {
static myname = "Person类的名字"
static mymethod = function () {
console.log("类的方法")
}
constructor(name, age) {
this.name = name
this.age = age
}
say() {
console.log(this.name, this.age)
}
}
// Person.myname = "Person类的名字"
// Person.mymethod = function () {
// console.log("类的方法")
// }
let obj = new Person("kerwin", 100)
console.log(obj)
Class继承
JS中的继承和JAVA非常相似,包含两个主要的关键字, extends 和 super ,直接上代码。
class Person {
static myname = "Person类的名字"
static mymethod = function () {
console.log("类的方法")
}
constructor(name, age) {
this.name = name
this.age = age
}
say() {
console.log(this.name, this.age)
}
}
class Student extends Person{
constructor(name,age,score){
super(name,age)
this.score = score
}
}
let obj = new Student("kerwin", 100,200)
如下图,继承到了属性方法和静态属性和方法。
对于方法的重写也是可以用到super关键字的
class Person {
static myname = "Person类的名字"
static mymethod = function () {
console.log("类的方法")
}
constructor(name, age) {
this.name = name
this.age = age
}
say() {
console.log(this.name, this.age)
}
}
class Student extends Person{
constructor(name,age,score){
super(name,age)
this.score = score
}
say(){
super.say()
console.log(this.score)
}
}
let obj = new Student("kerwin", 100,200)
这里关于实例obj调用的say方法遵循就近原则。