类
javascripts和 java的类的不同>>>
js类基于原型:连接
java基于类:复制
ES5中的仿类结构:构造器(自定义类型)
function hacker(name,age){
this.name=name;
this.age=age;
}
hacker.prototype.introduce=function(){
console.log(`我叫${this.name}`)
}
const one = new hacker("sagasw",21);
const two = new hacker("kok",17);
ES6中类的写法
class hacker{
constructor(name,age){
this.name=name;
this.age=age;
}
introduce(){
console.log(`我叫${this.name}`)
}
}
const one = new hacker("sagasw",21);
const two = new hacker("kok",17);
js中class语法注意:
类语法注意事项
1,类声明不会提升
2,类声明中的代码都自动运行在严格模式下
3,调用类必须使用new
4,类中所有的方法都是不可枚举的
5,类中的方法是不能用new调用的
6,在类的方法中重写类名报错
标准实例:
const Dog = (function(){
"use strict";//严格模式下
const Dog = fuction(name,age){
if(!(this instanceof Dog)){
throw new Error("必须用new去调用方法")
}
this.name=name;
this.age=age;
}
Object.defineProperty(Dog.prototype,"bark",{
value:function(){
if(this instanceof Dog.prototype.bark){
throe new Error("不能使用new调用")
}
console.log(`我叫${this.name}`)
},
enumerable:false
})
return Dog;
})()
类表达式
const Cat = class{
constructor(age){
this.age=age;
}
}
const xiaomiao = new Cat(1);
类为一等公民:
可以作为参数传给函数
能作为函数返回值
能给变量赋值
静态成员
const sag = class{
static kok(age){
this.age=age;
}
}
const xx = new sag(1);
因为静态成员的缘故,xx将无法获取age
getter与setter
getter 是一种获得属性值的方法,setter是一种设置属性值的方法
getter>>>>>>>
const sag = class{
constructor(name,age){
this.age=age;
this.name=name;
}
get galarxy(){
console.log(`你的名字:${this.name}`);
}
}
const xx = new sag(1);
setter>>>>>>
const sag = class{
constructor(name,age){
this.age=age;
this.name=name;
}
set galarxy(){
console.log(`你的名字:${this.name}`);
}
}
const xx = new sag(1);
扫描二维码关注公众号,回复:
10819267 查看本文章