Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var str = 'abced ';
Var obj = new String (str );
Function newToString (){
Return 'hello, world ';
}
Function func (val ){
Val. toString = newToString;
}
Func (str); // ps: only the str value is input, therefore, the toString modification is meaningless and the input str is equivalent to the method of modifying the copy of one of its replicas without affecting the original calculation results.
Alert (str. toString (); // The result is abced.
Func (obj); // ps: an object reference (str itself, or the memory address) is passed in. Therefore, the toString modification of the object will affect the later alert (obj. toString ()
Alert (obj. toString (); // The result is hello, world
</Script>
Appendix:
Value Type and reference type in JavaScript
Data Type value/reference type Remarks
The undefined value has no value.
Number Value
Boolean Value
String ValueStrings are processed by reference type in the value assignment operation.
Function Introduction
Object Introduction
Js value type and reference type
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <ptml> <pead> <meta http-equiv = "content-type" content = "text/html; charset = gb2312 "> <title> basic type/reference type -- Value Type </title> </pead> <body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Variables of the value type directly Save the value of the variable. References held by the referenced variable (you can compare the pointer of c/c ++, a "key "), you can quickly find the memory area of the stored content through reference.
The value type is usually fixed in bytes. The reference type usually stores arrays, objects, and functions, which are hard to know the amount of memory occupied.
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <ptml> <pead> <meta http-equiv = "content-type" content = "text/html; charset = gb2312 "> <title> basic type/reference type -- reference type </title> </pead> <body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Special string type between types in 2:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <ptml> <pead> <meta http-equiv = "content-type" content = "text/html; charset = gb2312 "> <title> basic type/reference type -- string </title> </pead> <body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Each time a new string is created-the object remains unchanged.
Supplement: For a string like "hello", when no variable references it (that is, the reference count is 0), it is time for garbage collection *-*