【问题标题】:How to implement multiple new functions in Javascript object?如何在 Javascript 对象中实现多个新功能?
【发布时间】:2014-02-03 10:11:12
【问题描述】:

我正在阅读一些关于在 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 class constructor prototype


【解决方案1】:

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); 

【讨论】:

  • 我知道我的构造函数不能有相同的名字。我已经更新了我的问题。声明第二个构造函数的新方法是/在 Javascript 中进行的正确方法吗?
  • @JVerstry:一般来说,new 在 js 中被认为是非惯用语,请参见 classic article
  • 好的,我明白了。我想在方法中添加一个带有默认值的选项参数是在不创建多个函数的情况下重现我想要的内容的最佳方法。谢谢。
猜你喜欢
  • 2012-11-02
  • 1970-01-01
  • 2020-08-24
  • 1970-01-01
  • 2017-06-22
  • 1970-01-01
  • 2014-04-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多