javascript中的构造函数

时间:2013-02-21 11:08:48

标签: javascript

如何在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
     }
    }

3 个答案:

答案 0 :(得分: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的{​​{1}}属性创建实例方法。

您可以阅读有关构造函数的更多信息 Simple “Class” Instantiation
Simple JavaScript Inheritance

您还可以使用

检查参数是否存在
function

答案 1 :(得分:1)

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

编写单个函数并检查收到的参数。

function A(a, b) {
    if (typeof a === "undefined") {
        // ...
    } else if (typeof b === "undefined") {
        // ...
    } else {
        // ...
    }
}

答案 2 :(得分: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