Class example

by MaxenceBrasselet

HTML

<script src="http://try.buildwinjs.com/lib/winjs/js/base.min.js?v1.0.70"></script>
<script src="http://try.buildwinjs.com/lib/winjs/js/ui.min.js?v1.0.70"></script>

JavaScript

WinJS.Namespace.define("MyNamespace", {
    MyClass: WinJS.Class.define(
        function(value) {
            // Constructor.
            //Attach properties to the current instance.
            MyNamespace.GetProperties(this, [this.obj]);
            
            this.value = value;
            this.values.push(value);
            this.obj[value] = "tryIt";
        },
        {
            //Prototype properties: This values are defined for all instance of this class.
            _private: true,
            unchangedValue: "initialValue",
            value: "",
            values: [],
            obj: {},
            test: function() {},
        },
        {
            //Static properties.
        }
    ),
    GetProperties: function(element, ignoreList) {
        for (var attr in element) {                              
            console.log("attr: ", attr, "typeof:", typeof element[attr], "value:", element[attr]);
            var value = element[attr];
            
            if (Array.isArray(value)) {
                element[attr] = [];
                continue;
            }
            
            if (value instanceof Object) {
                element[attr] = {};
                continue;
            }          
        }
    },
});

var first = new MyNamespace.MyClass("value1");
console.log("FIRST -> value: ", first.value, "FIRST -> values: ", first.values, "FIRST -> obj: ", first.obj);

var second = new MyNamespace.MyClass("value2");
// When we create the second instance we can see that the first instance has also a new value in its table.
// This is because the value array is linked to the prototype so every isntance share it.
// When we do the this.value = value in the constructor, we assign a value property to the instance.
console.log("FIRST -> value: ", first.value, "FIRST -> values: ", first.values, "FIRST -> obj: ", first.obj);
console.log("SECOND -> value: ", second.value, "SECOND -> values: ", second.values, "SECOND -> obj: ", second.obj);