javascript对象封装的方法:1、使用常规封装,代码为【function Person (name,age,sex)】;2、常见的方法,代码为【constructor : Person,_init_ :function(info)】。

本教程操作环境:windows7系统、javascript1.8.5版,DELL G3电脑。 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里面申明,哪来的呢??? 相关免费学习推荐:javascript视频教程
以上就是javascript对象封装的方法有哪些的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章! |