JavaScript中的多态性具有不同的构造函数

时间:2013-11-19 06:49:24

标签: javascript oop

我是JavaScript的新手,我一直在使用Java和C ++,我们在构造函数中有多态性;例如:

class Car
{
     Car()
     {
         ....
         //body
         ....
     }
     Car(int speed, string body_type)
     {
          ....
          //body
          ....
     }
};

我在JavaScript中尝试使用相同的概念进行面向对象编程。我写了这段代码:

<html>
<head>
    <script type="text/javascript">
    function bike()
    {
        this.bike_type="scooter";
    this.bike_bidy="metal";
        this.bike_speed=40;
        document.write('bike instantiated with type:'+this.bike_type);  
    }
    function bike(type, body, speed)
    {
        this.bike_type=type;
        this.bike_bidy=body;
        this.bike_speed=speed;
        document.write('bike instantiated with type:'+type);    
    }
    bike1 = new bike("harley","metal",120);
    bike2 = new bike();
    document.write(bike1.bike_type);
    document.write(bike2.bike_speed);
</script>
</head>
<body>
</body>
</html>

但是在这里,我只为bike() 函数/类而不是bike(type, body, speed)获取实例。当我尝试这个时:

<html>
<head>
    <script type="text/javascript">
    function bike(type, body, speed)
    {
        this.bike_type=type;
        this.bike_bidy=body;
        this.bike_speed=speed;
        document.write('bike instantiated with type:'+type);    
    }
    function bike()
    {
        this.bike_type="scooter";
    this.bike_bidy="metal";
        this.bike_speed=40;
        document.write('bike instantiated with type:'+this.bike_type);  
    }
    bike1 = new bike("harley","metal",120);
    bike2 = new bike();
    document.write(bike1.bike_type);
    document.write(bike2.bike_speed);
</script>
</head>
<body>
</body>
</html>

然后我得到function bike(type, body, speed)的实例而不是bike()。我明白这只是第一个定义。而且我不允许这样做。

如何在JavaScript中创建多态构造函数?有可能吗?

2 个答案:

答案 0 :(得分:4)

在Javascript中:

  • 全局函数只能定义一次
  • 函数参数是可选的
  • 函数参数可通过名为arguments的伪数组获得(参见the docs)。

所以你可以这样做:

function bike(type, body, speed)
{
    if (arguments.length >= 3) {
        this.bike_type = type;
        this.bike_body = body;
        this.bike_speed = speed;
        document.write('bike instantiated with type:'+type);    
    } else {
        this.bike_type = "scooter";
        this.bike_body = "metal";
        this.bike_speed = 40;
        document.write('bike instantiated with type:'+this.bike_type);  
    }
}

答案 1 :(得分:3)

不,这是不可能的。在这两种情况下,第二个函数定义都会覆盖第一个函数。

你必须从你的函数中检查你的参数,并相应地改变你的函数行为。

在您的情况下,如果没有给出默认值,您可以使用默认值:

function bike(type, body, speed)
{
    this.bike_type = type || "scooter";
    this.bike_bidy = body || "metal";
    this.bike_speed = speed || 40;
}

使用单个选项参数(例如bike({body: "carbon fiber"}))也很常见,允许您省略前导参数,而无需在其位置指定undefined

function bike(options)
{
    this.bike_type = options.type || "scooter";
    // ...
}