I want to know how to create a private attribute in a Javascript class. I tried this:
function Class1(selector)
{
//calling the constructor
Constructor();
//private attribute
var $container = null;
function Constructor()
{
$container = $(selector);
//Shows that container is an object
alert($container);
}
function Foo()
{
//Shows that container is null
alert($container);
}
result {
Foo : Foo
};
}
I supposed that in "Constructor" it creates a new variable $container and assign the object to it. I want to know how I am suposed to assign the value to the attribute $container of the object and not the local variable in the function Constructor.
this is because you first call Constructor()
and after that you assign null
to $container
If you switch that around you will get the desired result:
function Class1(selector) {
var container = null; //private attribute
constructor(); //calling the constructor
function constructor() {
container = $(selector);
console.log($container); //Shows that container is an object
}
function foo() {
console.log(container); //Shows that container is null
}
result { Foo : foo };
}
such as red-X already told: you have to execute the constructor after initialization of the container variable.
In my example: is is a better practice to use console.log
for debugging..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.