gpt4 book ai didi

javascript - 带有原型(prototype)的 Object.create()

转载 作者:行者123 更新时间:2023-11-30 10:29:20 25 4
gpt4 key购买 nike

我一直在玩 javascript 中的继承,现在我一直在玩 Object.create,我得到了这个场景

var Car = function() {
this.constructor = function(value) {
this._val = value;
this.accelerate = false;
};
};

Car.prototype.accelerate = function() {
this.accelerate = true;
};

Car.prototype.getVal = function() {
return this._val;
};

var myCar = Object.create(Car);

如果我尝试 myCar.getVal() 不起作用,我会收到一条错误消息,指出该对象中不存在该方法?为什么会这样?最后,哪种是使用 Object.create() 的正确方法?

最好的问候。

最佳答案

您永远不会在 Car 中调用 Car 或分配给 this.constructor 的函数,因此其中的代码永远不会运行,并且您在任何对象上都看不到 _valaccelerate

你做这件事的方式通常不是你做构造函数的方式。 Car 通常是 构造函数,例如:

var Car = function(value) {  // Added parameter, otherwise `value` was coming from nowhere
this._val = value;
this.accelerating = false; // Side note: Changed so it doesn't conflict with the method
};

当然,有了构造函数,您就不需要使用Object.create。只需通过 new 调用该函数:

var myCar = new Car(42);

这大致相当于:

var myCar = Object.create(Car.prototype);
Car.call(myCar, 42);

通常当你使用 Object.create 时,你没有像构建器那样多的构造函数,像这样:

var carProto = {
accelerate: function() {
this.accelerating = true; // Side note: Changed so it doesn't conflict with the method
},
getVal: function() {
return this._val;
}
};

function Car(value) {
var c = Object.create(carProto);
c._val = value;
return c;
}

var myCar = Car(42);

关于javascript - 带有原型(prototype)的 Object.create(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17882112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com