Saturday, July 13, 2019

[JavaScript][Example] Prototype, namespace, sub-namespace

JavaScript is a prototype-oriented programming, you can also call it as classless programming, instanse-base programming. Since it is a classless programming, you can't create "Class" in javascript but you can amend the prototype to act as the feature of class: Reusable.

Here is an example to amened prototype:

<script>
var Person = Person || {};
Person.event = {
    age:0,
    gender:'M',
    getAge:function(){
       console.log("getAge() is called, and the age is "+this.age);
    },
    setAge:function(age){
       this.age = age;
       console.log("New age is "+this.age);
    }
}
Person.subEvent = {
    age:0,
    gender:'M',
    getAge:function(){
       console.log("getAge() is called, and the age is "+this.age);
    },
    setAge:function(age){
       this.age = age;
       console.log("New age is "+this.age);
    }
}
Person.event.getAge();
Person.event.setAge(9);
Person.event.getAge();
console.log(Person.event.age);
</script>

var Person = Person || {}; is to create a global object and preform a checking: if Person is
defined just use it; otherwise, create an empty object.
you can call it a global namespace
Person.event or Person.subEvent are sub-namepace, you can add some variable, function into it.
GolbalNameSpace.subNameSpace.function
GolbalNameSpace.subNameSpace.variable
Person.event.getAge()
Person.event.age

Result :

No comments :

Post a Comment