【问题标题】:javascript classes how to declare variable or how to include a constructor in a class definitionjavascript类如何声明变量或如何在类定义中包含构造函数
【发布时间】:2012-02-08 09:34:10
【问题描述】:

我正在用javascript写一个日期类

我正在尝试编写这样的代码

var bdate = {

    var today = null,

    //want a construction here

    init : function()
    {
        //this.today = some processing
    },

    isLesser : function()
    {

    }
}

希望我已经在代码中明确了我的问题。

我们可以用这种风格的代码来做吗?它叫什么? javascript 中的类或...?

此外,我编写的类不是这样,而是像原型设计......

我已经看到在 javascript 中处理类的方法有很多种,我使用过但不知道为什么它们应该这样编码或它们的概念名称。

所以我总是反复试验,有时它会起作用,然后我使用该代码。

我想知道如何在上面的代码中包含一个构造函数。

请给点建议……

【问题讨论】:

标签: javascript prototype


【解决方案1】:

我看到你已经回答了你自己的问题,但我强烈建议你使用 JavaScript 中内置的 Date Object 并避免创建自己的问题。

【讨论】:

    【解决方案2】:

    这是我喜欢使用的一种模式:

    (function(window){
    
      // Constructor
      function BDate(){
        this.today = new Date();
        // blah blah
      }
    
      // Object of methods, attached to the Bdate's prototype. You can think of these methods as instance methods.
      Bdate.prototype = {
        isLesser: function(){
    
        },
    
        isGreater: function(){
    
        }
      };
    
    
      // We're inside an anonymous function, so window has no access to our class. So, we assign the constructor function to a window var of the same name:
      window.BDate = BDate;
    })(window);
    
    // We can now use the class like so:
    var myDate = new BDate(),
        herDate = new BDate();
    
    myDate.isLesser();
    herDate.isGreater();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-09
      • 2018-11-04
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 2019-10-22
      • 2012-04-05
      • 1970-01-01
      相关资源
      最近更新 更多