[英]Access private attribute Javascript OOP
I want to know how to create a private attribute in a Javascript class. 我想知道如何在Javascript类中创建私有属性。 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. 我以为在“构造函数”中它会创建一个新变量$ container并将对象分配给它。 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.
我想知道如何将值分配给对象的属性$ container而不是函数Constructor中的局部变量。
this is because you first call Constructor()
and after that you assign null
to $container
这是因为您首先调用
Constructor()
,然后将null
分配给$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. 例如red-X已经告诉过:您必须在初始化容器变量之后执行构造函数。
In my example: is is a better practice to use console.log
for debugging.. 在我的示例中:使用
console.log
进行调试是一种更好的做法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.