[英]Access private attribute Javascript OOP
我想知道如何在Javascript类中创建私有属性。 我尝试了这个:
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
};
}
我以为在“构造函数”中它会创建一个新变量$ container并将对象分配给它。 我想知道如何将值分配给对象的属性$ container而不是函数Constructor中的局部变量。
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 };
}
例如red-X已经告诉过:您必须在初始化容器变量之后执行构造函数。
在我的示例中:使用console.log
进行调试是一种更好的做法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.