我想知道这是否可行.
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]
Run Code Online (Sandbox Code Playgroud)
我不需要数字(7)来返回7,但它会很好.
首先return num;对您的代码没有影响.函数返回的对象是this.如果构造函数未显式返回对象,则它将始终隐式返回this(请参阅MDN文档中的步骤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;
};
Run Code Online (Sandbox Code Playgroud)
覆盖的额外好处valueOf是JavaScript将在内部将此方法调用到将对象转换为原始值.
例如,在正常添加中使用实例作为操作数也可以工作(而不是调用.add):
> var n = new MyNumber(7);
> n + 10
17
Run Code Online (Sandbox Code Playgroud)
也就是说,如果你只是想为原始类型创建一个包装器,那就不要这样做了.
正如pimvdb在他的评论中提到的那样,严格的比较会失败(例如).这是可以预料的和的原因之一,以避免原始值(的对象版本Number,String,Boolean)(即"foo" === new String("foo")是false为好).对象根本不像基元,混合这些会产生更复杂的代码.