访问私有属性Javascript OOP

Access private attribute Javascript OOP

本文关键字:Javascript OOP 属性 访问      更新时间:2023-09-26

我想知道如何在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
    };
}

我假设在"Constructor"中,它创建了一个新的变量$container并将对象分配给它。我想知道如何将值分配给对象的属性$container,而不是函数Constructor中的本地变量。

这是因为您首先调用Constructor(),然后将null分配给$container

如果你改变这一点,你会得到想要的结果:

http://jsfiddle.net/R8RG5/

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进行调试是一种更好的做法。。