Object to Primitive conversion: valueOf/toString

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.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容