JavaScript toLocaleString方法

JavaScript toLocaleString方法教程

JavaScript 中,Object.toLocaleString 方法用来返回一个该 对象字符串 表示。此方法被用于派生对象为了特定语言环境的目的(locale-specific purposes)而重载使用。

JavaScript toLocaleString详解

语法

obj.toLocaleString();

参数

参数 描述
obj 要转换的对象。

返回值

一个表示该对象的字符串。

说明

Object toLocaleString 返回调用 toString() 的结果。

案例

Object.toLocaleString输出对象字符串

使用 Object.toLocaleString 输出对象字符串

<!DOCTYPE html> <html> <head> <title>JavaScript 重写 Object.toString 方法</title> <script type="text/javascript"> console.log("嗨客网(www.haicoder.net)"); function createPerson(name, age, sex){ var person = new Object(); person.name = name; person.age = age; person.sex = sex; person.toLocaleString = function(){ return "Person toLocaleString, I am " + this.name + " i am " + this.age + " years old " + " and my sex is " + this.sex; } return person; } var person = createPerson("HaiCoder", 109, "F"); console.log(person.toLocaleString()); </script> </head> </html>

程序运行后,控制台输出如下:

23_JavaScript Object toLocaleString.png

我们使用 createPerson 方法,创建了了一个对象,同时,我们重写了该对象的 toLocaleString 方法,其中 toLocaleString 方法不接受任何参数,但是返回一个字符串类型的数据。

最后,我们使用 person 对象调用其 toLocaleString 方法,并打印。

JavaScript toLocaleString方法总结

在 JavaScript 中,Object.toLocaleString 方法用来返回一个表示该对象的字符串。