Javascript 自动转换数字[重复]

问题描述 投票:0回答:2

我知道如何控制任何对象在 javascript 中转换为

String
的方式:

var Person = function(firstName, lastName, age, heightInCm) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.heightInCm.heightInCm;
};
Person.prototype.toString = function() {
    return this.firstName + ' ' + this.lastName;
};

var friend = new Person('Bob', 'Johnson', 41, 183);

// Will automatically treat `friend` as a string using `Person.prototype.toString`
console.log(`Meet my friend ${friend}. He's SUPER AWESOME!!`);

如您所见,

friend
自动转换为
String
。我的问题是:数字是否存在相同的功能?

我可以看到

String
实例能够自动转换为
Number
:

>>> 5 * '5'
25

但我不确定如何在自定义对象上实现这种自动转换。以下不起作用:

Person.prototype.toNumber = function() {
    return this.age;
};

console.log(friend * 2); // Intended to be 82, but the result is NaN

如何让自定义对象自动转换为数字?

javascript casting
2个回答
5
投票

您需要覆盖

valueOf

Person.prototype.valueOf = function() {
    return this.age;
}

更多信息请访问 MDN


0
投票

您必须重写原型中的 valueOf 方法:

Person.prototype.valueOf = function() {
    return this.age;
};
© www.soinside.com 2019 - 2024. All rights reserved.