龙空技术网

web开发之-js类的实现方式

踢球的打工仔 129

前言:

现在小伙伴们对“php里写js”大概比较关切,朋友们都想要知道一些“php里写js”的相关文章。那么小编也在网摘上网罗了一些对于“php里写js””的相关内容,希望朋友们能喜欢,小伙伴们快快来了解一下吧!

自从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属于原型链继承。

标签: #php里写js #js类的方法