CNode

这道javascript题该如何解?

分享
Tthink2011发布于12 年前最后回复12 年前8 回复4618 浏览0 收藏

题目

var foo = new Foo(2);     // foo.val = 2;
var boo = new Foo(3);    // boo.val = 3;

foo + boo // => 结果必须是 5

解决方案模板

var Foo = function(value) {
  this.val = value;
}
查看回复

回复 (8)

H
hainee#1·12 年前

var foo = function(value) { this.val = value; this.toString = function() { return this.val; } }; try it……

B
bnuhero#3·12 年前
引用 haineevar foo = function(value) { this.val = value; this.toString = function() { return this.val; } };...

@hainee

最好是覆盖valueOf,而不是toString

var Foo = function(value) {
	this.value = value;
	this.valueOf = function() {
		return this.value;
	}
};

// 测试
var foo = new Foo(2);
var bar = new Foo(3);

console.log(foo + bar);
W
wuliao49#4·12 年前

楼上的是正道,但我有个变态 var Foo = function(val){return val == 2 ? [] : [5]}

A
alsotang#5·12 年前
W
wuliao49#7·12 年前
引用 alsotang@wuliao49 为何是返回数组?返回 0 和 5 不是更直观吗

@alsotang 用new的话,直接返回 0 和 5是拿不到的,数组可以。

R
ruanyl#8·12 年前

改变constructor的返回值不是个好方法,虽然目的看起来达到了。。

var Foo = function(value) {
  this.val = value;
  return new Number(value);
}
参与回复
登录后即可参与回复。登录