gpt4 book ai didi

javascript - 将对象内的两个属性相乘

转载 作者:行者123 更新时间:2023-12-03 12:33:26 26 4
gpt4 key购买 nike

我的自行车方法有两个属性。前齿轮和后齿轮。我想要另一个属性,这是一个称为齿轮比属性的新属性,可以通过将前齿轮和后齿轮数字相乘来获得。我编写的代码给出了连续错误。如何修复它。

function write() {
var bicycle = {
price: 20000,
model: "raleigh",
front_gear: 3,
rear_gear: 7,
gear_ratio: function () {
ratio: this.front_gear * this.rear_gear,
}
}
document.write("this is a " + bicycle.gear_ratio.ratio + " speed bike");
}
window.onload = write;

最佳答案

    gear_ratio: function () {
return this.front_gear * this.rear_gear
}
document.write("this is a " + bicycle.gear_ratio() + " speed bike");

这是我能推荐你做的最好的事情了。如果您仍然想要一个对象:

    gear_ratio: function () {
return {
ratio: this.front_gear * this.rear_gear
}
}
document.write("this is a " + bicycle.gear_ratio().ratio + " speed bike");

可以这样写:

function bike(settings){
// Make settings an object so we can use it always
if (typeof settings != 'object')
settings = {}

// if settings has a price use that, otherwise use 0
this.price = settings.price || 500;

this.model = settings.model || "custom";

this.front_gear = settings.front_gear || 2;

this.rear_gear = settings.rear_gear || 2;

this.__defineGetter__("gear_ratio", function(){
return this.front_gear * this.rear_gear;
});

}

function write() {
var bike1 = new bike({
price: 20000,
model: "raleigh",
front_gear: 3,
rear_gear: 7,
});
var bike2 = new bike({
front_gear: 3,
});
document.write("<br /> bike 1 is a " + bike1.gear_ratio + " speed bike by " + bike1.model + " costing " + bike1.price);
document.write("<br /> bike 2 is a " + bike2.gear_ratio + " speed bike by " + bike2.model + " costing " + bike1.price);
}

隐含函数调用的地方,但这将要求您的自行车是一个实际的实例化类,并且不能在每个浏览器中工作,并且更难以调试。如果您需要更好的解释,请告诉我。

关于javascript - 将对象内的两个属性相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23831871/

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