这两种方法有什么不同

What is the difference betwen two methods?

本文关键字:什么 两种 方法      更新时间:2023-09-26

我可以直接调用Date对象的解析方法,如下所示:

    alert(Date.parse("March 21, 2012"));

但是我不能这样做:

    alert(Date.getTime()); // TypeError: Date.getTime is not a function

这就是我让它工作的方式:

    alert(new Date().getTime()); // works well

那么,为什么我不能像Date.parse()那样直接调用Date.getTime()呢?

基本问题:我已经写了一个类,我想直接使用它的一些方法,比如上面的Date.parse()。

getTimeDate.prototype中,在构造new Date()对象时使用。

parseDate本身中,因此是直接调用的,而不是从构造的对象中调用。

这里有一篇关于JavaScript原型的文章,供您阅读。

在面向对象编程中,前者被称为静态方法,而后者被称为实例方式。实例方法要求对象的实例已经实例化(因此new Date()调用是必要的)。静态方法没有此要求。

基本问题:我已经写了一个类,我想直接使用它的一些方法,比如上面的Date.parse()。

编写完类后,要添加静态方法,您需要执行以下操作:

MyClass.myStaticFunction = function() {
    // Contents go here.
}
正如其他人所指出的,JavaScript使用原型来定义实例方法。但是,您可以定义静态方法,如下所示。我并不是想在这里定义整个Date对象,而是展示它的实例和静态函数是如何定义的。
// constructor defined here
function Date() {
    // constructor logic here
}
// this is an instance method
DateHack.prototype.getTime = function() {
    return this.time_stamp;
}
// this method is static    
Date.parse = function(value) {
    // do some parsing
    return new Date(args_go_here);
}
function Class() {
    this.foo = function() { return 123; };
}
Class.bar = function() { return 321; };
Class.bar(); // 321
( new Class ).foo(); // 123