开发者

valueOf not working when i do alert(obj)?

开发者 https://www.devze.com 2023-03-26 08:01 出处:网络
This gives \"[object Object]开发者_开发知识库\": <!doctype html> <script> var a={}; a.valueOf=function(){

This gives "[object Object]开发者_开发知识库":

<!doctype html>
<script>
var a={};
a.valueOf=function(){
    return "asd";
};
alert(a);
</script>

but this gives "asd":

<!doctype html>
<script>
var a={};
a.valueOf=function(){
    return "asd";
};
alert(""+a);
</script>

i can understand why i get "asd" in the second example. But in the first example, shoudn't i also get "asd" since i'm putting the object through the alert function (which basically ends up calling the value-of anyway) ?


Override toString() to achieve result you need:

var a={};
a.toString=function(){
    return "asd";
};
alert(a);

And look at this valueOf() vs. toString() in Javascript


When you use the + operator, JavaScript uses valueOf, and otherwise when a String is expected from an object, JavaScript uses toString(). Internally, perhaps in the Object.prototype.valueOf, it is designed to be the same as toString(). So, if you define only toString(), but not valueOf(), JavaScript will use toString() for both '+' (because internally valueOf calls toString) and in contexts where a String is expected. However, if you define valueOf, then that will be used where there is a '+' (or a - or / or any other arithmatic operator). But it won't be used when it expects a String (as in case of alert). It will call toString().


"a" is an object so alert in case one is showing object, by doing alert(""+a) you are forcing "a" to be treated as string


""+a returns a string type. use typeof() to check this.

http://jsfiddle.net/zYs73/

<div id='t'></div>

 <script>
    var a={};
    a.valueOf=function(){
        return "asd";
    };
    alert(a);
    document.getElementById('t').innerHTML += "<br/>" + typeof(a);

    var b={};
    b.valueOf=function(){
        return "asd";
    };
    alert(""+b);
    document.getElementById('t').innerHTML += "<br/>" +  typeof(""+b);
</script>


by doing ""+ you are trying to alert a string and with + you are trying to cast any values in string and then added to empty string ""

0

精彩评论

暂无评论...
验证码 换一张
取 消