利用闭包实现私有变量

在js中不存在private 私有变量的定义,但利用闭包可以模拟

var getter, setter;
(function(){
	var privateA = 0;
	getter = function(){
		return privateA;
	};
	setter = function(newVal){
		if(typeof newVal != 'number'){
			throw new Error("不是number")
		}
		privateA = newVal;
	}
})();

猜你喜欢

转载自blog.csdn.net/weixin_42043407/article/details/121405928