Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapper Object Explicit Creation

Tags:

javascript

What i have understood about wrapper object is:if we declare a primitive type and access some properties then wrapper object is created internally and once the operation is done it is discarded e.g.

var str1="Stack"
str1.length=10
str1.length

The third line will give me 5 because second line operation is done on temporary object and third line will create a new temporary object.

But if i create my own wrapper object explicitly e.g.

var str1=new String("Stack")
str1.length=100
str1.length

Then also why i'm getting 5. Here i have no dependency of internal temporary wrapper object which discards on opertaion completion. Here i have dedicate wrapper object then why it is not allowing me to assign length value and if we can't set length then why Javascript allows me to set length??Could any one elaborate on this.

like image 783
user2485435 Avatar asked Oct 18 '25 21:10

user2485435


1 Answers

According to javascript specification string length is unchanging. Therefore your code "str1.length = value" does nothing.

Creation of string via constructor--- var str1=new String("Stack")--- or via normal creation --- var str1="Stack" --- creates different types of object. But since their prototype are same (proto: String), length is still unchanging.

length

The number of elements in the String value represented by this String object.

Once a String object is initialized, this property is unchanging. It has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

See below example code:

var str1 = "Stack"
var str2 = new String("Stack")
str1 === str2
false
typeof str1
"string"
typeof str2
"object"
str1
"Stack"
str2
String {0: "S", 1: "t", 2: "a", 3: "c", 4: "k"
, length: 5
, [[PrimitiveValue]]: "Stack"}0: "S"1: "t"2: "a"3: "c"4: "k" length: 5
__proto__: String
[[PrimitiveValue]]: "Stack"
like image 148
Atilla Ozgur Avatar answered Oct 21 '25 11:10

Atilla Ozgur