вторник, 21 марта 2017 г.

Примитивы в Javascript

If primitives have no properties, why does "abc".length return a value?

Because JavaScript will readily coerce between primitives and objects. In this case the string value is coerced to a string object in order to access the property length. The string object is only used for a fraction of second after which it is sacrificed to the Gods of garbage collection – but in the spirit of the TV discovery shows, we will trap the elusive creature and preserve it for further analysis…
[3/21/17, 3:31:08 PM] Igor Morgun: String.prototype.returnMe= function() {
    return this;
}

var a = "abc";
var b = a.returnMe();

a; //"abc"
typeof a; //"string" (still a primitive)
b; //"abc"
typeof b; //"object"

Комментариев нет:

Отправить комментарий