美文网首页
Object to Primitive conversion:

Object to Primitive conversion:

作者: Time_Notes | 来源:发表于2024-02-13 15:04 被阅读0次

    Object to Primitive Conversion:

    In JavaScript, when you use an object in a context where a primitive value is expected (e.g., in arithmetic operations or when comparing to a primitive value), JavaScript performs an implicit object-to-primitive conversion.

    Object to primitive conversion in JavaScript allows you to control how an object is converted to a primitive value in various contexts. This can be controlled by defining two methods on your object: toString and valueOf.

    const obj={

    valueOf:function(){

        return 42;// This method is called for numeric operations

    },

    toString:function(){

        return "Hello";// This method is called for string operations

    }

    };

    console.log(obj+2);// 44, because valueOf is called for numeric operation

    console.log(obj+" World");// "Hello World", because toString is called for string operation

    In this example, the valueOf method is used when performing numeric operations, and the toString method is used when performing string operations.

    相关文章

      网友评论

          本文标题:Object to Primitive conversion:

          本文链接:https://www.haomeiwen.com/subject/lgnvpdtx.html