自从es6出现之后,js里就有了class这个可以用来定义类对象,其实在编译完之后,最早是使用的闭包方式来实现的,今天我们就来讲解两种在js中实现类的写法。
class实现js类
class Person{
constructor(name)
{
this.name = name;
console.log("我是父类的构造函数");
}
}
class Student extends Person{
constructor(name){
super(name);
console.log("我是student的构造函数");
}
shout(){
console.log("我的名字是:"+this.name);
}
get age(){
console.log("我是getter");
return this._age;
}
set age(val){
console.log("我是setter",val);
this._age = val;
}
}
var student = new Student("zsf");
student.age = 99;
console.log(student.age);
student.shout();
function实现js类
var Person = function(){
var Person = function(name)
{
this.name = name;
console.log("我是父类构造函数");
}
Person.prototype.name = "";
return Person;
}();
var Student = function(){
var Student = function(name){
Person.prototype.constructor.call(this,name);
console.log("我是子类构造函数");
}
Student.prototype ={
get age(){
console.log("我是getter");
return this._age;
},
set age(val){
console.log("我是setter",val);
this._age = val;
}
}
Student.prototype.shout=function(){
console.log(this.name);
}
return Student;
}();
var student = new Student("zsf");
student.age = 99;
console.log(student.age);
student.shout();
注:js中没有接口的概念,但是在ts(typescrpt)中是有接口的概念,ts是js的超级,更新近于我们常见的高级语言的oop的写法,类如java,c#,php等!我们以上用两种写法写了js实现类和继承,以及getter和setter写法,class的写法,大家如果看过之前的php编程就比较好理解了。function闭包的写法,主要是依据于js中的prototype对象,这个是js实现oop的核心,你即使用class的写法,其内部也是基于prototype的写法来写的!在大家可以把prototype理解成extend的意思,某个function的prototype=obj,表示这个function里包含了obj里的属性和方法。prototype属于原型链继承。
限 时 特 惠: 本站每日持续更新海量各大内部创业教程,一年会员只需98元,全站资源免费下载 点击查看详情
站 长 微 信: lzxmw777
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。