Polymorphism in JavaScript(javascript中的多态)

Introduction

Polymorphism in Object-Oriented Programming is the ability to create a variable, a function, or an object that has more than one form.

Background

The primary usage of Polymorphism in Object-Oriented Programming is the ability of objects belonging to different types to respond to methods, fields, or property calls of the same name, each one according to an appropriate type-specific behaviour.

The programmer does not have to know the exact type of the object in advance, and so the exact behaviour is determined at run-time. This is what we call late binding or dynamic binding (this make Polymorphism a very cool feature). Requirements are such that, there must be properties with the same name and the same parameter sets in all the superclasses, subclasses and interfaces.

Using the code

As far as JavaScript is concerned, we really don’t have interfaces as in other programming languages but we do have superclasses and subclasses. Going back to my article on JavaScript Inheritance, we have created classes that inherit from others.

Let’s reuse the same example, this time we will create a class Person then another class called Manager that inherits from Person. Both classes will include a method called wake_up(). We will then create objects of both types and put them in an array.

When we loop through that array, the system will call the function wake_up() on each of the objects and the implementation will be determined dynamically.

Let’s define our class Person.

  Person = function (id, name, age) {
            this.id = id;
            this.name = name;
            this.age = age;
           // alert('A new person has been accepted');
        }
        /* definition of our Person class */
        Person.prototype = {
            /** wake person up */
            wake_up: function () {
                alert('A person is awake');
            },
            /** retrieve person's age */
            get_age: function () {
                return this.age;
            }
        }

Now let us create an Inheritance class so that other classes can inherit from our class person. For more details and demo on inheritance, refer to my article on JavaScript Inheritance by clicking here.

Inheritance_Manager = {};  
           
Inheritance_Manager.extend = function (subClass, baseClass) { 
                function inheritance() { }
                inheritance.prototype = baseClass.prototype;
                subClass.prototype = new inheritance();
                subClass.prototype.constructor = subClass;
                subClass.baseConstructor = baseClass;
                subClass.superClass = baseClass.prototype; }

Ok we are then going to define our class Manager as follows:

Manager = function (id, name, age, salary) {
          Manager.baseConstructor.call(this, id, name, age);
          this.salary = salary;
          // alert('A manager has been registered.'); 
}

Our class Manager will inherit from Person as follows:

Inheritance_Manager.extend(Manager, Person);

Let’s add more functionality and overwrite our wake_up() function

 Manager.prototype = {
    wake_up: function () {
        alert('I am in control with Polymorphism');
    }
 }

Now we create an array and store in objects of type Person and Manager.

var arrPeople = new Array();
arrPeople[0] = new Person(1, 'Joe Tester', 26);
arrPeople[1] = new Manager(1, 'Joe Tester', 26, '20.000');

See how the function wake_up() behaves based on the different objects we have. This is what we callPolymorphismPolymorphism makes things so simple when you have many objects that present the same interface but different implementations.

for (var i in arrPeople) {
   arrPeople[i].wake_up();
   alert(arrPeople[i].get_age());
}

Many people don’t believe that JavaScript is fully-fledged Object Oriented Programming Language but I thinkJavaScript just does things its own way which is different from other languages. As we can see in the case ofPolymorphism here, there is no difference with other programming languages. So it is fully polymorphic.

Here is the complete code:

     /** This is our Person class */
            Person = function (id, name, age) {
                this.id = id;
                this.name = name;
                this.age = age;
               // alert('A new person has been accepted');
            }
            /* definition of our Person class */
            Person.prototype = {
                /** wake person up */
                wake_up: function () {
                    alert('A person is awake');
                },
                /** retrieve person's age */
                get_age: function () {
                    return this.age;
                }
            }    

            Inheritance_Manager = {};   

            Inheritance_Manager.extend = function (subClass, baseClass) { 
                function inheritance() { }
                inheritance.prototype = baseClass.prototype;
                subClass.prototype = new inheritance();
                subClass.prototype.constructor = subClass;
                subClass.baseConstructor = baseClass;
                subClass.superClass = baseClass.prototype;
            }    

            Manager = function (id, name, age, salary) {
                Manager.baseConstructor.call(this, id, name, age);
                this.salary = salary;
               // alert('A manager has been registered.');
            }    

            Inheritance_Manager.extend(Manager, Person);    

            Manager.prototype = {
                wake_up: function () {
                    alert('I am in control');
                }
            }    

            var arrPeople = new Array(); 
            arrPeople[0] = new Person(1, 'Joe Tester', 26);
            arrPeople[1] = new Manager(1, 'Joe Tester', 26, '20.000');    

            for (var i in arrPeople) {
                arrPeople[i].wake_up();
                alert(arrPeople[i].get_age());
            }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


转贴:http://www.codeproject.com/Articles/315169/Polymorphism-in-JavaScript



注:

运行代码的时候报错,应该是把上面的一段代码:

            Manager.prototype = {
                wake_up: function () {
                    alert('I am in control');
                }
            }    
改成:
Manager.prototype.wake_up = function(){
    alert('I am in control');
};




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值