[英]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.