类
这里对js的类定义进行相关的阐述。一共有好几种方法,实现对js的类定义。
构造函数法
这里实现构造函数方法,实现对js的类定义。
function?Cat()?{
this.name?=?"大毛";
}
上方定义一个相关的类,该类的名称为Cat。
新建对象
var?cat1?=?new?Cat();
alert(cat1.name);?//?大毛
这里新建了一个Cat对象,并进行打印。
添加属性
通过原型链的方法,实现对类添加相关的属性或者函数。
Cat.prototype.makeSound?=?function(){
alert("喵喵喵");
}
这样就实现了对一个类的生成。
Object.create()
通过Object.create()自动生成对应的对象。
新建相关的类。
var?Cat?=?{
name:?"大毛",
makeSound:?function(){?alert("喵喵喵");?}
};
然后再新建Object.create相关的类,创建新的对象。
var?cat1?=?Object.create(Cat);
alert(cat1.name);?//?大毛
cat1.makeSound();?//?喵喵喵
这样就完成了新的对象的创建。
最简单的方法
通过定义一个function,模拟一个类
var?Cat?=?{
createNew:?function(){
//?some?code?here
}
};
定义对象,模拟静态方法
var?Cat?=?{
createNew:?function(){
var?cat?=?{};
cat.name?=?"大毛";
cat.makeSound?=?function(){?alert("喵喵喵");?};
return?cat;
}
};
这里进行相关的调用
var?cat1?=?Cat.createNew();
cat1.makeSound();?//?喵喵喵
这样就完成了对类相关的定义。
继承
定义一个父类
var?Animal?=?{
createNew:?function(){
var?animal?=?{};
animal.sleep?=?function(){?alert("睡懒觉");?};
return?animal;
}
};
在其属性调用相关的方法,完成指向
var?Cat?=?{
createNew:?function(){
var?cat?=?Animal.createNew();
cat.name?=?"大毛";
cat.makeSound?=?function(){?alert("喵喵喵");?};
return?cat;
}
};
调用父类的相关的方法
var?cat1?=?Cat.createNew();
cat1.sleep();?//?睡懒觉
私有属性
私有属性,通过创建函数来实现
var?Cat?=?{
createNew:?function(){
var?cat?=?{};
var?sound?=?"喵喵喵";
cat.makeSound?=?function(){?alert(sound);?};
return?cat;
}
};
上方创建的内部变量,外部无法访问
var?cat1?=?Cat.createNew();
alert(cat1.sound);?//?undefined
最新方法 class
这里采用class方法完成。通过一个class关键字完成对类的定义
//?匿名类
let?Example?=?class?{
constructor(a)?{
this.a?=?a;
}
}
//?命名类
let?Example?=?class?Example?{
constructor(a)?{
this.a?=?a;
}
}
静态方法
添加static关键字
class?Example?{
//?新提案
static?a?=?2;
}
//?目前可行写法
Example.b?=?2;
通过static,实现对类的成员属性的访问。
get和set
get和set必须同时出现
class?Father?{
constructor(){}
get?a()?{
return?this._a;
}
}
class?Child?extends?Father?{
constructor(){
super();
}
set?a(a)?{
this._a?=?a;
}
}
let?test?=?new?Child();
test.a?=?2;
console.log(test.a);?//?undefined
class?Father1?{
constructor(){}
//?或者都放在子类中
get?a()?{
return?this._a;
}
set?a(a)?{
this._a?=?a;
}
}
class?Child1?extends?Father1?{
constructor(){
super();
}
}
let?test1?=?new?Child1();
test1.a?=?2;
console.log(test1.a);?//?2
继承
这里使用super实现继承
class?Child2?extends?Father?{
constructor(){
super();
//?调用父类普通方法
console.log(super.test());?//?0
}
static?test3(){
//?调用父类静态方法
return?super.test1+2;
}
}
Child2.test3();?//?3
小明菜市场
推荐阅读
●目标 | Node.js web 应用 Docker 化
●新知 | JavaScript 几种循环方式以及模块化的总结
●优雅 | koa处理异常
●知新 | Koa 框架从入门到熟练第二章
领取专属 10元无门槛券
私享最新 技术干货