类、静态和继承的封装学习
ES5原生类方法
function Foo(name,cname) {
/*构造函数里面的方法和属性*/
this.name=name;
this.cname=cname;
this.run=function(){
console.log(`${this.name}---${this.cname}`)
}
}
let arr =new Foo('未来学习','首席全栈设计师');
/*实例方法是通过实例化来调用的,静态是通过类名直接调用*/
arr.run();
//输出:未来学习---首席全栈设计师
在类上增加方法和属性,用prototype方法:
foo.prototype.school='东京大学人工智能计算机';
foo.prototype.work=function(){
console.log(`${this.name}---${this.cname}---${this.school}`);
}
arr.work();
//输出:未来学习---首席全栈设计师---东京大学人工智能计算机
增加一个静态方法:
/*静态方法*/
Foo.sub=function(){
console.log('这个方法目前还不知道怎么用');
}
Foo.sub();
//输出:这个方法目前还不知道怎么用
所有代码:
function Foo(name,cname) {
/*构造函数里面的方法和属性*/
this.name=name;
this.cname=cname;
this.run=function(){
console.log(`${this.name}---${this.cname}`)
}
}
/*实例方法是通过实例化来调用的,静态是通过类名直接调用*/
let arr =new Foo('未来学习','首席全栈设计师');
arr.run();
Foo.prototype.school='东京大学人工智能计算机';
Foo.prototype.work=function(){
console.log(`${this.name}---${this.cname}---${this.school}`);
}
arr.work();
/*静态方法*/
Foo.sub=function(){
console.log('这个方法目前还不知道怎么用');
}
Foo.sub();
ES5原生继承
function Foo(name,school) {
this.name=name;
this.school=school;
this.run=function(){
console.log(this.name+'--'+this.school);
}
}
function Web(name,school){
/*对象冒充实现继承*/
Foo.call(this,name,school);
}
Web.prototype=new Foo();
let arr=new Web('未来学习','东京大学');
arr.run();
ES6写法(非常简洁):
class Foo{
/*类的构造函数,实例化的时候执行,new的时候执行*/
constructor(name,cname) {
this._name=name;
this._cname=cname;
}
_Name(){
console.log(this._name,this._cname);
}
}
let arr=new Foo('未来学习','最棒的分享');
arr._Name();
静态方法:
class Foo{
/*类的构造函数,实例化的时候执行,new的时候执行*/
constructor(name,cname) {
this._name=name;
this._cname=cname;
}
_Name(){
console.log(this._name,this._cname);
}
/*内部静态方法*/
static _work(){
console.log('内部静态方法');
}
}
let arr=new Foo('未来学习','最棒的分享');
arr._Name();
/*外部静态资源*/
Foo.arr = "外部静态方法";
console.log(Foo.arr);
/*内部静态方法*/
Foo._work();
ES6继承:
class Foo{
constructor(name,age){
this.name=name;
this.age=age;
}
getInfo(){
console.log(`姓名:${this.name} 年龄:${this.age}`);
}
run(){
console.log('run')
}
}
class Web extends Foo{ //继承了Person extends super(name,age);
constructor(name,age,content){
super(name,age); /*实例化子类的时候把子类的数据传给父类*/
this.content=content;
}
print(){
console.log(this.content);
}
}
var w=new Web('未来学习','1','开张有1岁了');
w.getInfo();
w.print();
单列:
class Db {
static getInstance(){ /*单例*/
if(!Db.instance){
Db.instance=new Db();
}
return Db.instance;
}
constructor(){
console.log('实例化会触发构造函数');
this.connect();
}
connect(){
console.log('连接数据库');
}
find(){
console.log('查询数据库');
}
}
var myDb=Db.getInstance();
var myDb2=Db.getInstance();
var myDb3=Db.getInstance();
var myDb4=Db.getInstance();
myDb3.find();
myDb4.find();
© 2020 www.f-learn.cn All Rights Reserved