JavaScript 之封装、继承、多态

封装

  封装的目的是要隐藏对象的属性和实现细节,仅对外公开接口,控制在程序中属性的读和修改的访问级别。在许多语言中也许提供了 private、public、protected 等关键字来提供不同的访问权限,但是 JavaScript 没有提供对这些关键字的支持,只能依赖变量的作用域来实现封装特性,而且也只能模拟出 public 和 private 这两种封装性。

  在 ES5 中实现封装:使用闭包方式实现

var Person = (function() {
   
	// 静态私有变量
	var shemale = 0;
	var abnormalityPerson = 0;
	// 静态私有方法
	function privateMethod() {
   
		console.log("调用静态私有方法 privateMethod.");
	}
	
	// 返回构造函数
	function _person(newId, newName, newAge, newGender) {
   
		// 私有变量
		var name, age, gender;
		// 私有方法 (对私有属性的操作)
		function checkId(id) {
   
			console.log("私有方法 checkId, id = " + id);
		}
		// 特权方法
		this.getName = function () {
   
			return name;
		}
		this.setName = function (newName) {
   
			name = newName;	
		}
		this.getAge = function () {
   
			return age;
		}
		this.setAge = function (newAge) {
   
			if(newAge >= 0 && newAge <= 120) {
   
				 age = newAge;	
			} else {
   
				abnormalityPerson ++;
			}
		}
		this.getGender = function () {
   
			return gender;
		}
		this.setGender = function (newGender) {
   
			if(newGender != "male" && newGender != "female") {
   
				 shemale ++;
			} else {
   
				gender = newGender;
			}	
		}
		// 共有属性
		this.id = newId;
		// 公有方法
		this.getParents = function () {
   
			console.log("公有方法 getParents 被调用。");
		}

		// 构造器
		this.setName(newName);
		this.setAge(newAge);
		this.setGender(newGender);
		
//		console.log("abnormalityPerson count: " + abnormalityPerson);
//		console.log("shemale count: " + shemale);
	}
	// 构建原型
	_person.prototype = {
   
		// 静态共有属性
		staticPerson: false,
		// 静态共有方法
		play : function () {
   
			console.log(this.getName() + "play.");
		}
	}
	// 返回类
	return _person;
})();

测试代码:

var person1 =<
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值