javascript 类、对象、私有成员、公有成员概念初解
对于javascript来说,它也有类和对象的之说,任何一个function都可以说是类,有类当然也就有构造函数,利用构造函数new出来的自然就是对象了。
类有private和public成员,private成员只能在类的作用域可以访问。对象的成员都是public公共成员,任何函数都可以访问和修改。这说起来都有点儿抽象,下面就来看看实例进而对私有成员变量、公有成员变量、类、对象几个概念进行解释:
function Container(param) {this.member = param;//publicvar secret = 3;//private function testPrivateMethod() { //private methodalert('private method!');}this.objectMethod = function testPublicObjectMethod(){ //public methodalert('this is a public Object method !');};}function testObject(param) {//alert(member);//member is not defined,直接在外部访问,就算是public变量也是不可见的,必须通过变量来访问var myContainer = new Container(param);alert(myContainer.member); //myContainer.member = 'ccccc'; //通过对象修改public成员变量//alert(myContainer.member);myContainer.objectMethod();//this定义的方法可见,var定义的方法不可见}Container.prototype.testPrototype = function() {alert("this is a public method from prototype!");};