javascript - Are strings objects? -
this question has answer here:
- how javascript string not object? 1 answer
here 2 reasons think strings objects. first, can create string in following way:
var mystring = new string("asdf");
i'm under impression constructor function following new operator has return object. second, strings seem have properties , methods. example:
mystring.touppercase();
but, if strings objects, we'd expect following work:
function string_constructor() { return "asdf"; } var mystring = new string_constructor();
but doesn't, , i've been told doesn't because strings aren't objects. strings objects or not? and, either way, how can make sense of i've listed?
speaking language types, strings values of string type.
the language has 5 primitive types, string, number, boolean, null , undefined.
there string objects (also number or boolean), called primitive wrappers, created when use constructor function associated them, example:
typeof new string('foo'); // "object" typeof 'foo'; // "string"
but don't confused them, rarely need use primitive wrappers, because if primitive values not objects, can still access inherited properties, example, on string, can access members of string.prototype
, e.g.:
'foo'.indexof('o'); // 2
that's because property accessor (the dot in case) temporarily converts primitive value object, being able resolve indexof
property in prototype chain.
about constructor function have in question, know, won't return string.
functions called new
operator return implicit value, new object inherits function's prototype
, example:
function test () { // don't return (equivalent returning undefined) } new test() instanceof test; // true, object
if object returned constructor, newly created object (this within constructor) lost, explicit returned object come out function:
function test2() { return {foo: 'bar'}; } new test2().foo; // 'bar'
but in case of primitive values, just ignored, , new object constructor implicitly returned (for more details check [[construct]]
internal operation, (see step 9 , 10)).
Comments
Post a Comment