2013-02-21 132 views
0

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

的JavaScript不是Java。期。你可能只有一个构造函数,但根据参数的类型选择不同的行为(例如'typeof a =='undefined') – madfriend 2013-02-21 11:11:01

回答

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

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>;创建。
可以使用构造函数functionprototype属性创建实例方法。

你可以阅读更多有关构造函数
Simple “Class” Instantiation
Simple JavaScript Inheritance

你也可以检查一个参数是否存在使用

if(paramB == undefined) { 
    //do something if paramB is not defined 
} 
+0

我认为第三行代码应该是'this.paramB = paramB'不能让2字符编辑修复它) – Grim 2013-02-21 11:18:18

+0

@Grim谢谢,修正。 – 2013-02-21 11:19:51

1

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

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

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