为什么不能直接调用Date.getMonth等相关方法呢?

今天在使用Date相关的方法的时候,突然产生以下疑问:

1.为什么不可以直接调用Date.getFullYear()等相关方法呢?

2.为什么直接调用原型上的方法也不行呢?比如:调用Date.prototype.getFulYear(),浏览器会产生以下错误

下面是Date的原型上的方法:

特来寻求帮助,还望先生们不吝赐教!

阅读 2.2k
3 个回答

getFullYear 在 Data.prototype 上,Date 没有这个方法。

getFullYear 要求 this 是一个 Date 对象(准确点说,是有一个 [[DataValue]] internal slot)。但 Date.prototype 并不是 Date 的对象。

没有为什么,人家代码里做了类型判断而已。你自定义的类型也可以做到:

class Foo {
}

Foo.prototype.bar = function() {
   if (!(this instanceof Foo)) throw 'this is not a Foo object.';

   console.log('bingo!');
}

new Foo().bar();     // bingo!
Foo.prototype.bar(); // error

P.S. 如果你是对 this 指向有疑问的话,那我建议是要打好基本功,this 是一个非常关键也非常基础的知识。

推荐问题