在Javascript中,每个对象都有一个valueOf()和toString()方法.我原以为每当调用字符串转换时都会调用toString()方法,但显然它被valueOf()所取代.
例如,代码
var x = {toString: function() {return "foo"; },
valueOf: function() {return 42; }};
window.console.log ("x="+x);
window.console.log ("x="+x.toString());
Run Code Online (Sandbox Code Playgroud)
将打印
x=42
x=foo
Run Code Online (Sandbox Code Playgroud)
这让我觉得倒退..如果x是一个复数,例如,我希望valueOf()给我它的大小,但每当我想转换成一个字符串我就会想要像"a + bi"这样的东西.而且我不想在隐含字符串的上下文中显式调用toString().
这只是它的方式吗?
我对JavaScript有点新,我有一个问题.
我知道你可以设置变量和"子变量".喜欢:
var msg = "Hello World";
alert(msg);
Run Code Online (Sandbox Code Playgroud)
并且
var msg = {
lipsum: "Lorem Ipsum Dolor Sit Amet"
}
alert(msg.lipsum);
Run Code Online (Sandbox Code Playgroud)
但我想知道你是否可以做到这两点,比如
var msg = "Hello World" || {
lipsum: "Lorem Ipsum"
}
alert(msg + msg.lipsum);
Run Code Online (Sandbox Code Playgroud)
这样,您可以声明一个变量,并将同一个变量作为一个对象.显然,我无法完成所做的事情,但你得到了图片.
任何帮助将非常感激!
我有这个Rational类,每个操作都有一个方法(add,mult等)
function Rational(nominator, denominator){
this.nominator = nominator;
this.denominator = denominator || 1;
}
Rational.prototype = {
mult: function(that) {
return new Rational(
this.nominator * that.nominator,
this.denominator * that.denominator
);
},
print: function() {
return this.nominator + '/' + this.denominator;
}
};
var a = new Rational(1,2),
b = new Rational(3);
console.log( a.mult(b).print() ); // 3/2
Run Code Online (Sandbox Code Playgroud)
我可以让它更"自然",例如启用console.log( a * b )吗?
javascript dsl operator-overloading fractions prototypal-inheritance