如何在JavaScript对象中实现多个新功能



我正在阅读JavaScript中的类创建。我知道这个概念在JavaScript中不存在,并且可以与prototype一起使用。

我正在尝试将以下代码从Java转换为JavaScript。具体来说,我想拥有两个构造函数,一个无参数,一个带有两个参数:

public class MyClass {
    int width = 10;
    int height = 20;
    public MyClass() { };
    public MyClass(int w, int h) {
        this.width = w;
        this.height = h;
    };
    ...
}
据我了解,

我需要定义我的"类",如javaScript中的以下内容:

function MyClass() {
    this.width = 10;
    this.height = 20;
};

但是,我如何定义第二个构造函数?我希望能够通过两种方式创建班级的实例:

var Instance1 = new MyClass();
var Instance2 = new MyClass(33,45);

更新:

好吧,我知道我的构造函数不能具有相同的名称,因为JavaScript无法识别不同的参数类型。因此,如果我为构造函数使用不同的名称,我应该如何宣布它们?以下是正确的吗?

function MyClass() {
    this.width = 10;
    this.height = 20;
};
MyClass.prototype.New2 = function(w,h) {
    var result = new MyClass();
    result.width = w,
    result.height = h,
    return result;
};

javaScript没有多途径,因此,您唯一的选择是解析参数并采取相应的行动。一个常见的成语是使用 ||检查参数是"空"(未定义或0):

function MyClass(w, h) {
    this.width = w || 10;
    this.height = h || 20;
};

如果0是您上下文中的有效值,请明确检查undefined

function MyClass(w, h) {
    this.width  = typeof w != 'undefined' ? w : 10;
    this.height = typeof h != 'undefined' ? h : 20;
};

另一个选项是将参数作为对象提供,并将其与"默认"对象合并。这是jQuery中的常见模式:

function MyClass(options) { 
  // set up default options 
  var defaults = { 
    width: 10,
    height: 20
  }; 
  var options = $.extend({}, defaults, options); 

最新更新