我想知道这是否可行。
number = function(n){
var num = n;
this.add = function(x){
return num + x;
}
return num;
}
alert(number(7)); //returns 7
seven = new number(7);
alert(seven.add(3)); // returns 10
alert(seven); // want this to return 7, but will return [object Object]
我不需要 number(7) 来返回 7,但这会很好。
最佳答案
第一个return num;
对您的代码没有影响。函数返回的对象是this
.如果构造函数不显式返回对象,它将始终隐式返回 this
(请参阅 MDN documentation 中的步骤 3)。
也就是说,您可以覆盖两种方法,即 toString
[MDN]和 valueOf
[MDN] :
function MyNumber(n){
this.num = n;
}
MyNumber.prototype.add = function(x){
return this.num + x; // or `this + x` since we implemented `valueOf`
};
// Is called whenever the object has to be converted to a string
// e.g. alert(myNumber) ; myNumber + " is the answer to all questions"
MyNumber.prototype.toString = function() {
return this.valueOf().toString(); // or `this.num.toString()`
};
// Is called whenever the object has to be converted to a primitive value
// e.g. myNumber + 42 ; myNumber == 42
MyNumber.prototype.valueOf = function() {
return this.num;
};
覆盖的额外好处 valueOf
是 JavaScript 也会在内部调用此方法,将对象转换为原始值。
例如,在正常加法中使用实例作为操作数也可以(而不是调用 .add
):
> var n = new MyNumber(7);
> n + 10
17
就是说,如果您只想为原始类型创建一个包装器,那么请不要那样做。
As pimvdb mentions in his comment ,严格比较会失败(例如)。这是可以预料的,也是避免原始值的对象版本( Number
、 String
、 Boolean
)的原因之一(即 "foo" === new String("foo")
也是 false
)。对象的行为根本不像基元,混合这些会产生更复杂的代码。
关于javascript - 创建一个有返回值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10961548/