2012-02-08 30 views
-1

我在javascriptJavaScript类如何声明变量或如何将一个类定义构造函数

我想写这样

var bdate = { 

    var today = null, 

    //want a construction here 

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

    isLesser : function() 
    { 

    } 
} 

希望我代码写日期一类在代码中明确表达了我的问题。

我们可以在这种风格的代码中做到这一点。它叫做什么?在JavaScript或...类吗?

此外,我编写的类不喜欢这一点,但像原型...

我看到有各种方式来应对JavaScript类和我使用,但不知道为什么他们应该编码的方式或他们的概念名称。

所以我总是做试验和错误,并在一个点上它的工作,然后我使用该代码。

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

建议请...

+0

而我在寻找,我发现其中有一个解决方案的另一个计算器链接的答案,但我还没有尝试... http://stackoverflow.com /问题/ 8380772 /怎么办-I-声明类式的JavaScript – 2012-02-08 09:35:54

回答

0

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

0

这里有我喜欢用一个模式:

(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(); 
相关问题