Object.prototype.toString(); と知る
1519 ワード
*mdnドキュメントを参照
toString()メソッドは、オブジェクトを表す文字列を返します.また、基本的にはすべてのオブジェクトが継承されています.
メソッドがcustom objectで再定義されていない場合、toString()[objecttype]を返します.ここでtypeはobjecttypeを表す.
サンプルコードで理解してください.
custom objectとして再定義したら...?
->デフォルトのメソッドに代わる関数を作成できます.
toString()メソッドはパラメータを受け入れず、文字列(string)を返さなければなりません.
値は必要な値とは関係ありませんが、オブジェクトに関する情報を渡すと便利です.
This function generates a string containing the name and age of the object, in the form "property = value'".
With the preceding code in place, any time toString() is used in a Person context, JavaScript automatically calls the personToString() function, which returns the following string:
toString()メソッドは、オブジェクトを表す文字列を返します.また、基本的にはすべてのオブジェクトが継承されています.
メソッドがcustom objectで再定義されていない場合、toString()[objecttype]を返します.ここでtypeはobjecttypeを表す.
サンプルコードで理解してください.
function person(name, age) {
this.name = name;
this.age = age;
}
const thePerson = new person('conut', 30);
console.log(thePerson);
console.log(thePerson.toString()); // return [object Object]
上のobjectは上書きされていないので、返されます.custom objectとして再定義したら...?
->デフォルトのメソッドに代わる関数を作成できます.
toString()メソッドはパラメータを受け入れず、文字列(string)を返さなければなりません.
値は必要な値とは関係ありませんが、オブジェクトに関する情報を渡すと便利です.
person.prototype.toString = function personToString() {
return `My name is ${this.name} and ${this.age}.`;
}
console.log(thePerson.toString());
this following code creats and assigns peronToString() to override the default toString() method.This function generates a string containing the name and age of the object, in the form "property = value'".
With the preceding code in place, any time toString() is used in a Person context, JavaScript automatically calls the personToString() function, which returns the following string:
"My name is conut and 30."
Reference
この問題について(Object.prototype.toString(); と知る), 我々は、より多くの情報をここで見つけました https://velog.io/@kimconut/Object.prototype.toString-이해하기テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol