0

如何在 JavaScript 中声明参数化构造函数?它是如何在 JavaScript 中实现的?

 public class A()
    {
     //variable declaration
     public A()
     {
      //do something
     }

     public A(int a)
     {
      //do something
     }

     public A(int a,int b)
     {
      //do something
     }
    }
4

3 回答 3

1

javascript中的任何函数都可以是构造函数

function A(paramA, paramB) {
    this.paramA = paramA;
    this.paramB = paramB;

    //do something
}

A.prototype.method1 = function(){
    console.log(this)
    console.log('Inside method 1' + this.paramA)
}

var a = new A(1, {name: 'Name'});
console.log(a.paramA);
console.log(a.paramB.name)
a.method1()

所有实例变量都可以使用this.<variable-name>=<value>;.
可以使用prototype构造函数的属性创建实例方法function

您可以阅读有关构造函数的更多信息
简单的“类”实例化
简单的 JavaScript 继承

您还可以使用检查参数是否存在

if(paramB == undefined) {
    //do something if paramB is not defined
}
于 2013-02-21T11:10:59.613 回答
1

JavaScript 不支持基于参数定义的重载。

编写一个函数并检查收到了哪些参数。

function A(a, b) {
    if (typeof a === "undefined") {
        // ...
    } else if (typeof b === "undefined") {
        // ...
    } else {
        // ...
    }
}
于 2013-02-21T11:12:28.393 回答
0
var Class = function(methods) {   
    var klass = function() {    
        this.initialize.apply(this, arguments);          
    };  

    for (var property in methods) { 
       klass.prototype[property] = methods[property];
    }

    if (!klass.prototype.initialize) klass.prototype.initialize = function(){};      

    return klass;    
};
var Person = Class({ 
    initialize: function(name, age) {
        this.name = name;
        this.age  = age;
    },
    initialize: function(name, age, gender) {
        this.name = name;
        this.age  = age;
        this.gender = gender;
    }
}); 

var alice = new Person('Alice', 26);
var rizwan = new Person('riz', 26, 'm');
alert(alice.name + ' - alice'); //displays "Alice"
alert(rizwan.age + ' - rizwan'); //displays "26"

http://jsfiddle.net/5NPpR/ http://www.htmlgoodies.com/html5/tutorials/create-an-object-oriented-javascript-class-constructor.html#fbid=OJ1MheBA5Xa

于 2013-02-21T11:27:27.563 回答