Javascript自动转换数字
我知道如何控制javascript中任何对象强制转换为Javascript自动转换数字,javascript,casting,Javascript,Casting,我知道如何控制javascript中任何对象强制转换为字符串的方式: var Person = function(firstName, lastName, age, heightInCm) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.heightInCm.heightInCm; }; Person.prototype.toString = function
字符串的方式:
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 bob = new Person('Bob', 'Johnson', 41, 183);
// Will automatically treat `bob` as a string using `Person.prototype.toString`
console.log('Meet my friend ' + bob + '. He\'s SUPER AWESOME!!');
如您所见,friend
自动转换为String
。我的问题是:数字是否也有同样的功能
我可以看到String
实例能够自动转换为Number
:
>>> 5 * '5'
25
但我不确定如何在自定义对象上实现这种自动转换。以下操作不起作用:
Person.prototype.toNumber = function() {
return this.age;
};
console.log(bob * 2); // Intended to be 82, but the result is NaN
如何允许自定义对象自动转换为数字?您需要覆盖valueOf
:
Person.prototype.valueOf = function() {
return this.age;
}
您必须覆盖prototype中的valueOf方法:
Person.prototype.valueOf = function() {
return this.age;
};
太快了!!太快了,我无法立即接受:PNote:valueOf
在许多情况下优先于toString
,因此如果你是数字,在任何需要数字或字符串的上下文中,你都是数字;如果可能存在歧义,您需要显式调用.toString()
。真的,这很快。。。我想我必须删除我的ansert哈哈哈很好!你说得对,我的问题和那个问题一模一样!