JavaScript 伪类模式

JavaScript Pseudoclasses Pattern

嗨,我是 JavaScript 的新手,我正在研究对象创建模式,特别是我专注于伪类模式,所以我写了几行代码来检查我是否理解了这个概念:

var Car = function (name, x, y) {
    this.name = name;
    this.x = x;
    this.y = y;
};

Car.prototype.drive = function (byX, byY) {
    this.x += byX;
    this.y += byY;
};

var ferrari = new Car("Ferrari", 5, 5);
ferrari.drive(5, 5);

var ferrari_proto = Object.getPrototypeOf(ferrari);
var ferrari_proto_proto = Object.getPrototypeOf(ferrari_proto);
var ferrari_proto_proto_null = Object.getPrototypeOf(ferrari_proto_proto);

console.log(ferrari_proto);                 // Should be Function
console.log(ferrari_proto_proto);           // Should be Object
console.log(ferrari_proto_proto_null);      // Should be Null

我从 运行 得到的代码是:

{ drive: [Function] }
{ }
null

并记录我得到的这些对象的类型:

object
object
object

现在,我认为以这种方式创建对象时,法拉利原型应该是 Car 函数,所以我的预期是:

function    // Tha Car function
object      // The Function prototype, that is Object
object      // null, that is the end of the chain

有人可以解释为什么我得到这些输出以及为什么我错了?!

the ferrari prototype would have been the Car function

不,您的 ferrari 原型(它继承的对象)是 Car.prototype - 您将 .drive 之类的方法放在那里。 Car构造函数与此不同

在JavaScript函数中,数组也被认为是对象。所以日志可能会返回基本类型。

这是了解使用 JavaScript 原型的好资源。

http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/