js类公有属性和私有属性

本文深入探讨JavaScript中的类结构,讲解如何创建公有和私有属性,重点在于利用模块模式实现类的封装,理解这些概念对于提升JavaScript编程能力至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

function Test(){
	var name = 'test'//私有
	this.age = 12//公有
	this.getName = function(){
		return name
	}
	this.getAge = function(){
		return this.age
	}
}

var Test = new Test()
print(Test.name)//undefined
print(Test.age)//12
print(Test.getAge())//12
print(Test.getName())//'test'

模块模式

var singleton = function(){
	//私有变量和函数
	var privateVariable = 10
	function privateFunction(){
		return false
	}

	//创建对象
	var object = new CustomType()

	object.publicProperty = true;
	object.publicMethod = function(){
		privateVariable++
		return privateFunction()
	}

	return object;

    //特权/公有方法和属性
	// return {
	// 	publicProperty:true,
	// 	publicMethod:function(){
	// 		privateVariable++
	// 		return privateFunction()
	// 	}
	// }
}()
//单例接口
var application = function(){
	//私有
	var components = new Array()
	components.push(new BaseComponent())//BaseComponent()作为初始化操作

	var app = new BaseComponent()

	app.getComponentCount = function(){
		return components.length
	}

	app.registerComponent = function(component){
		if(typeof component == "object"){
			components.push(component)
		}
	}

	return app

	// return {
	// 	getComponentCount:function(){//返回已注册的组件数
	// 		return components.length
	// 	},
	// 	registerComponent:function(component){//注册新组件
	// 		if(typeof component == "object"){
	// 			components.push(component)
	// 		}
	// 	}
	// }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值