这两种方法有什么不同
What is the difference betwen two methods?
我可以直接调用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()。
getTime
在Date.prototype
中,在构造new Date()
对象时使用。
parse
在Date
本身中,因此是直接调用的,而不是从构造的对象中调用。
这里有一篇关于JavaScript原型的文章,供您阅读。
在面向对象编程中,前者被称为静态方法,而后者被称为实例方式。实例方法要求对象的实例已经实例化(因此new Date()
调用是必要的)。静态方法没有此要求。
基本问题:我已经写了一个类,我想直接使用它的一些方法,比如上面的Date.parse()。
编写完类后,要添加静态方法,您需要执行以下操作:
MyClass.myStaticFunction = function() {
// Contents go here.
}
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
相关文章:
- 这两种不同的创建对象文字的方法有什么区别
- 这两种方法有什么不同
- 这两种使用 jQuery 追加 DOM 元素的方法有什么不同
- 什么'这两种继承策略之间的区别是什么
- 这两种风格在Javascript中编写函数的区别是什么
- 什么'这两种对象构造方法之间的区别是什么
- 用两种方式保存对象,有什么区别
- 在敲除js中,这两种编码方法有什么区别
- 这两种用 JavaScript 编写原型函数的方式有什么区别?
- 这两种调用 JavaScript 匿名函数的类型有什么区别
- 这两种创建元素的方法有什么区别
- 这两种实现之间有什么区别
- 调用事件侦听器 - 两种方式之一起作用,有什么区别
- JavaScript/jQuery中的两种格式有什么区别
- 这两种说法有什么区别
- D3这两种数据绑定方式有什么区别
- javascript中的两种OO方法有什么区别
- 两种形式的自调用函数调用之间的区别是什么
- 对象定义有两种方式-有什么区别
- 这两种JavaScript模式的优缺点是什么