Constructors in JavaScript objects

后端 未结 19 1721
夕颜
夕颜 2020-11-22 10:21

Can JavaScript classes/objects have constructors? How are they created?

19条回答
  •  孤街浪徒
    2020-11-22 10:43

    http://www.jsoops.net/ is quite good for oop in Js. If provide private, protected, public variable and function, and also Inheritance feature. Example Code:

    var ClassA = JsOops(function (pri, pro, pub)
    {// pri = private, pro = protected, pub = public
    
        pri.className = "I am A ";
    
        this.init = function (var1)// constructor
        {
            pri.className += var1;
        }
    
        pub.getData = function ()
        {
            return "ClassA(Top=" + pro.getClassName() + ", This=" + pri.getClassName()
            + ", ID=" + pro.getClassId() + ")";
        }
    
        pri.getClassName = function () { return pri.className; }
        pro.getClassName = function () { return pri.className; }
        pro.getClassId = function () { return 1; }
    });
    
    var newA = new ClassA("Class");
    
    //***Access public function
    console.log(typeof (newA.getData));
    // function
    console.log(newA.getData());
    // ClassA(Top=I am A Class, This=I am A Class, ID=1)
    
    //***You can not access constructor, private and protected function
    console.log(typeof (newA.init));            // undefined
    console.log(typeof (newA.className));       // undefined
    console.log(typeof (newA.pro));             // undefined
    console.log(typeof (newA.getClassName));    // undefined
    

提交回复
热议问题