JavaScript中实现私有属性的写类方式(2)
上一篇写了个工具函数$class,这篇再完善以下。实现以下功能
1,继承
2,子类继承父类时,不继承父类的私有属性
/** * @param {String} className * @param {String/Function} superCls * @param {Function} classImp */ function $class(className, superCls, classImp){ if(superCls === '') superCls = Object; function clazz(){ if(typeof this.init == "function"){ this.init.apply(this, arguments); } } var p = clazz.prototype = new superCls(); var _super = superCls.prototype; window[className] = clazz; classImp.apply(p, [_super]); }
先写个父类
/** * 父类 Person */ $class('Person','',function(){ // 私有属性age var age; this.init = function(n, a){ // 公有属性name this.name = n; // 私有属性初始化 age = a; }; this.getName = function(){ return this.name; }; this.setName = function(name){ this.name = name; } this.getAge = function(){ return age; }; this.setAge = function(a){ age = a; }; });
写子类,继承于Person
$class("Man",Person, function(supr){ var school; this.init = function(n, a, s){ supr.init.apply(this, [n,a]); school = s; } this.getSchool = function(){ return school; }; this.setSchool = function(s){ school = s; }; });
new一个子类实例
var m = new Man('tom', 25, 'pku'); console.log(m.name); // tom 继承父类的共有属性name可以直接使用点操作符获取 console.log(m.age); // undefined 父类的私有属性age不能直接使用点操作符获取 console.log(m.getAge()); // 25 可通过父类的共有方法getAge获取私有属性age console.log(m.school); // undefined Man自己的私有属性仍然不能通过点操作符获取 console.log(m.getSchool()); // pku 通过getSchool()方法获取私有属性school