javascript - So is string object type or primitive type? -


this question has answer here:

from javascript: definitive guide david flanagan

javascript types can divided 2 categories: primitive types , object types. javascript’s primitive types include numbers, strings of text (known strings), , boolean truth values (known booleans).

it states string primitive type. later on there example code

var s = "hello, world" // start text. s.charat(0) // => "h": first character. s.charat(s.length-1) // => "d": last character. s.substring(1,4) // => "ell": 2nd, 3rd , 4th characters. s.slice(1,4) // => "ell": same thing s.slice(-3) // => "rld": last 3 characters s.indexof("l") // => 2: position of first letter l. s.lastindexof("l") // => 10: position of last letter l. s.indexof("l", 3) // => 3: position of first "l" @ or after 3 

so string object type or primitive? how can primitive type have methods? isn't object type property? if it's kind of hybrid of both, when primitive , when object?

strings primitive values:

4.3.2 primitive value

member of 1 of types undefined, null, boolean, number, or string

but there string objects, objects , not primitives:

4.3.18 string object

member of object type instance of standard built-in string constructor

it may seem primitive strings have properties, no.

when use example string.charat(0), string object created same value primitive string. object inherits string.prototype. charat method of string object called, , returned value returned in string.charat(0). string object removed.

when assign property primitive string, similar happens: property assigned new string object instead of primitive.

some examples:

var primitivestr = 'foo',     objectstr = new string('foo'); typeof primitivestr; // 'string' typeof objectstr; // 'object' typeof primitivestr.charat; // 'function' typeof objectstr.charat; // 'function' primitivestr.foo = objectstr.foo = 123; typeof primitivestr.foo; // 'undefined' typeof objectstr.foo; // 'number' 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -