首页 > 编程开发 > JavaScript    日期:2021-04-30 / 来自互联网 / 浏览

javascript对象封装的方法:

常规封装

function Person (name,age,sex){
    this.name = name;
    this.age = age;
    this.sex = sex;
}
 
Pserson.prototype = {
    constructor:Person,
    sayHello:function(){
        console.log('hello');
    }
}

这种方式是比较常见的方式,比较直观,但是Person() 的职责是构造对象,如果把初始化的事情也放在里面完成,代码就会显得繁琐,如果放在一个方法里初始化会不会好点呢?

升级版 (常见)

function Person (info){
    this._init_(info);
}
 
Pserson.prototype = {
    constructor : Person,
    _init_ : function(info) {
        this.name = info.name;
        this.age = info.age;
        this.sex = info.sex;
    }
    sayHello:function(){
        console.log('hello');
    }
}

可是,说到这里就发现,name,age,sex 并没有在Person里面申明,哪来的呢???

觉得上面的内容有用吗?快来点个赞吧!

点赞() 我要打赏

温馨提示 : 本站内容来自会员投稿以及互联网,所有源码及教程均为作者总结编辑,请大家在使用过程中提前做好备份,以免发生无法预知的错误,源码类教程请勿直接用于生产环境!

 可能感兴趣的文章