gpt4 book ai didi

JavaScript - 原型(prototype)函数与 ViewModel 函数?

转载 作者:行者123 更新时间:2023-11-28 15:08:45 26 4
gpt4 key购买 nike

我想知道是否有理由更喜欢原型(prototype)函数/viewModel 函数而不是其他函数。

假设您想将整数 1234 表示为货币值,例如 12.34€

我所做的是,在 Number 对象上创建一个原型(prototype)函数:

Number.localeSeparator = 1.1.toLocaleString().substr(1, 1);

Number.prototype.centToEuro = function (separator_string) {
if (!separator_string) {
separator_string = Number.localeSeparator;
}
return (this / 100).toFixed(2).replace(".", separator_string) + "€";
}

var vm = {myMoney: ko.observable(1234)};
ko.applyBindings(vm);

这使得数据绑定(bind)相当容易,因为我在 View 中需要做的就是:

<div data-bind="text: myMoney().centToEuro()"></div>

但是除了原型(prototype)函数之外,我还可以使用几乎相同的代码创建一个 viewModel 函数,如下所示:

var vm = {
myMoney: ko.observable(1234),
localeSeparator: 1.1.toLocaleString().substr(1, 1),
centToEuro: function (value_int, separator_string) {
if (!separator_string) {
separator_string = vm.localeSeparator;
}
return (value_int / 100).toFixed(2).replace(".", separator_string) + "€";
}
}
ko.applyBindings(vm);

在 View 中使用,它看起来像这样:

<div data-bind="text: centToEuro(myMoney())"></div>

正如您所知,两个 HTML 行的长度几乎完全相同,只是方法不同。所以问题是,更喜欢哪种方法?

最佳答案

鉴于 centToEuro 与任意数字无关,而是与您在这里处理的特定货币模型有关,并且您不应该扩展内置原型(prototype)对象,请使用 viewmodel 函数.

关于JavaScript - 原型(prototype)函数与 ViewModel 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37631459/

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