Javascript: does it create a string with a new value? Do I need to release it later?

If I create an object Stringusing, say,

var temp = new String('ABCD');

Does this create memory space for this object String, such as objects in JavaScript? If so, can I free this object by simply assigning this variable β€œtemp” to zero ie temp = null?

+3
source share
4 answers

Does this create memory space for this String object, such as Objects in Javascript?

String objects are objects.

If so, can I free this object by simply assigning this variable β€œtemp” to zero ie temp = null?

Garbage collection works as usual.

+4
source

, JavaScript String . , , .

+1

( Wrapper), [[Class]], , temp = "ABCD"
, , null , , . ? (null - )
delete temp , ,

+1

, JS , . , , null .

new String() , , - :

  • equals
  • typeof yields 'object' 'string'

, ,

var a = new String('hello'), b = new String('hello');
var strA = String('hello'), strB = String('hello');
var literalA = 'hello', literalB = 'hello';

// Outputs false, because the string is wrapped by an object,
// it not the primitive
console.log( a == b );
// Proof that it not the primitive string, outputs 'object'
console.log(typeof a);

// Using String() and the literal yield consistent results
console.log( strA == strB); //outputs true
conole.log( literalA == literalB); // outputs true
console.log( typeof strA); // outputs 'string'
console.log( typeof literalA ); // outputs 'string'

// You can compare literal and string from String(xxxx)
console.log( strA == literalA)

, , , valueOf() .

console.log(a.valueOf() == b.valueOf()); // outputs true;

, , .

console.log(a.constructor == String); // outputs true

Just be careful if you work with frames, pop-ups, iframes, for each window object there is a different String constructor, i.e.

// outputs false
console.log( window.frames.frameA.String == window.frames.frameB.String)
+1
source

Source: https://habr.com/ru/post/1792537/


All Articles