Learning Ext JS 3

Private and privileged methods in JavaScript Más videos

Descripción del tema

This is a well known topic for many developers, but some people don't think we can define private methods and privileged methods in JavaScript. In today's chapter we will learn how to hide properties and methods of an object.

Private properties and methods

To create private properties or methods we do it in the constructor, the parameters and ordinary variables (the ones we create using the keyword "var") are private properties that cannot be accessed outside of the object. The private methods are functions inside of the constructor, this kind of functions won't be available outside of the object. Let's see the next example:
//The object User
var User = function(options){
	//private properties
	var name = options.name;
	var password = options.password;
	//public property
	this.user = options.user;
	
	//private method
	function privateMethod(){
		console.debug('im a private method!')
	}
}

//new instance of User
var u = new User({name:'Crysfel',password:'***',user:'cvilla'});

console.debug(u.user); //cvilla
console.debug(u.name); //undefined
console.debug(u.privateMethod()); //throws error
In the previous example we added two properties and one private method, when we try to print them in the Firebug console we can see that the properties are not displayed and the method throws an error; this is how we can hide the information inside of an object.

Privileged Methods

Douglas Crockford defines privileged methods as the methods that are public and at the same time can have access to the private properties and manipulate them, this methods are created dynamically because they're added to the object at runtime. Let's see an example of this:
var Person = function(options){
	//private properties
	var name = options.name
	var birthYear = options. birthYear;
	//private method
	var calculateAge = function(){
		var today = new Date();
		return today.getFullYear() - birthYear;
	}
	//Privileged method
	this.getAge = function(){
		return calculateAge(); //calling private method
	}
 }
 
 //new Person instance
 var p = new Person({name:'Peter', birthYear:1983});
 
 console.debug(p.getAge());// the age
 console.debug(p.name);// undefined
 console.debug(p. birthYear);// undefined
The privileged methods are very important and an excellent tool to have access to private information, this is the way we can expose needed information. It is important to remember that the privileged methods are created at runtime because they are defined in the object's constructor and not in the prototype (prototype object). In the next example we will create dynamically getter and setters for the properties that the constructor receives as the parameter "options".
var Animal = function(options){
	//a private method to do the job 
	//and to create a new scope (see last chapter of this course)
	function createGetterAndSetters(properties,property){
		//attach the getter for the current property
		this['get'+property] = function(){
			return properties[property];
		}
		//attach the setter for the current property
		this['set'+property] = function(value){
			properties[property] = value;
		}
	}
	//iterate through the options
	for(var property in options){
		//call the private method with the right context
		createGetterAndSetters.call(this,options,property);
	}
}

//two different instances of Animal object
var zul = new Animal({breed:'Chihuahua',gender:'female',name:'Zul'});
var rocky = new Animal({breed:'Beagle',gender:'male',name:'Rocky'});

console.debug(zul.getbreed());//Chihuahua
console.debug(zul.getname());//Zul
console.debug(zul.name);//undefined
console.debug(rocky.getbreed());//Beagle
console.debug(rocky.getgender());//male
console.debug(rocky.getname());//Rocky
console.debug(rocky.breed);//undefined
In the previous example we created dynamically the getter and setters of the properties that are received as a parameter in the constructor using a private method to do the job and create a new el scope at runtime making it possible to have access to correct values, (if you have any questions of the concept scope I recommend you to go back to that chapter). Another important part of the example is the for loop, because we are invoking the private method to assign the proper context, in this way we are making sure that the variable "this" inside of the private method is referencing the object "Animal" (if you have any questions about this concept I also recommend you to read the chapter about the context).

Conclusions

Thanks to the "closures" that JavaScript handles, it is possible to create private methods and properties as well as privileged methods, because they allow access to external variables of the parent function even if it has completed its execution. The private and privileged methods can only be defined in the constructor (because of the concepts mentioned before), the public methods can be added at any moment using the object "prototype". We have learn how to hide information in an object and we have used different concepts of previous chapters like the el scope, el contexto, closures; it is important to remember these concepts because we will be using them later on in this course. Also we will see more tools that Ext JS has to manage these terms easily. As always your suggestions, questions or comments are very welcome and your vote for us in Digg or your favorite social network.

Te gustaría recibir más tutoriales como este en tu correo?

Este tutorial pertenece al curso Learning Ext JS 3, te recomiendo revises el resto de los tutoriales ya que están en secuencia de menor a mayor complejidad.

Si deseas recibir más tutoriales como este en tu correo te recomiendo registrarte al curso, si ya eres miembro solo identifícate y registrate al curso, si no eres miembro te puedes registrar gratuitamente!

Si no gustas registrarte en este momento no es necesario! Aún así puedes recibir los nuevos tutoriales en tu correo! Jamás te enviaremos Spam y puedes cancelar tu suscripción en cualquier momento.

¿Olvidaste tu contraseña?

Se el primero en comentar!

Instructor del curso

Crysfel3

Autor: Crysfel Villa

Software engineer with more than 7 years of experience in web development.

Descarga Código Fuente

Regístrate a este curso

Este tutorial pertenece al curso Learning Ext JS 3, revisa todos los tutoriales que tenemos en este mismo curso ya que están en secuencia y van de lo más sencillo a lo más complicado.

Tendrás acceso a descargar los videos, códigos y material adicional.

Podrás resolver los ejercicios incluidos en el curso así como los Quizzes.

Llevarás un registro de tu avance.