Wednesday, April 27, 2011

Javascript object-based programming for C# object-oriented programmers

<script>

    
    function individual(msg) // class individual
    {
        this.mx = msg;    // mx is a public property of class individual instance
        var zuper = this.mx + '!'; // zuper is a private property of class individual instance
        
        this.show = function() { // public method
            alert(zuper);
        }
        
        this.showSomething = function() { // public method
            alert(this.something);
            quick();
        }
        
        function quick() { // private method
            alert('quick');
        }
    }

    var x = new individual("Hello");
    var y = new individual("World");
    
    alert(x.mx); // shows Hello
    alert(y.mx); // shows World
    
    alert(x.zuper); // shows undefined    
    y.zuper = "xxx"; // but this one creates a different instance of outside zuper on y's instance, but this is different from y's inside zuper
    alert(y.zuper); // shows xxx
    
    
    x.show(); // shows "Hello!"
    y.show(); // to prove that the outside zuper instance on y is different from inside(acts like a private property), this will not show "xxx", this shows "World!"
    
    y.something = "George"; // you can attach properties on javascript's object on whim
    y.showSomething(); // shows "George"
    
    y.quick(); // this will make javascript terminate silently
    alert("Not shown"); // won't get executed 
    
</script>

No comments:

Post a Comment