Tuesday, December 20, 2011

Prototype of Javascript

Recently I just try to dig my knowledge of JavaScript deeper. Prototype is a very important concept of JavaScript and is the key to program JavaScript in object-oriented way. After reading some articles I did the code snippets for experiment.

Reference articles:
Understand JavaScript Article
OO programming in JavaScript

My experiment code:

<script type="text/javascript">
    function employee(name,jobtitle,born){
       this.name=name;
       this.jobtitle=jobtitle;
       this.born=born;
    }
    var fred=new employee("Fred Flintstone","Caveman",1970);

    employee.prototype.salary=300;

    document.write(fred.name + "'s salary:" + fred.salary);
    document.write('<br/>');

    var jack = new employee("Jack","Developer",1983);
    jack.salary=100;

    document.write("Prototype(defaultsuper class static) salary: " + jack.__proto__.salary);
    document.write('<br/>');
    document.write(jack.name + "'s salary:" + jack.salary);
    document.write('<br/>');

    employee.prototype.aftertax = function(){
        return this.salary * 0.8;
    };

    document.write(jack.name + "'s after tax salary: " + jack.aftertax());
    document.write('<br/>');
</script>

No comments:

Post a Comment