Javascript assigning value to primitive

后端 未结 2 539
情话喂你
情话喂你 2021-01-27 06:16

If JavaScript will readily coerce between primitives and objects why adding properties to it results to undefined??

var a = \"abc\";
var b = a.length
console.log         


        
相关标签:
2条回答
  • 2021-01-27 06:29

    Why don't you do it like this?

    var abc=Number(3);
    abc.foo="bar";
    
    abc; //3
    abc.foo; //bar
    

    @Bergi indeed, sorry for this. I've missed the new statement. Here it is:

    var abc=new Number(3);
    abc.foo="bar";
    
    abc; //3
    abc.foo; //bar
    

    At least it works just right. I don't know what else someone may need :) primitives... coercion... blah.

    0 讨论(0)
  • 2021-01-27 06:33

    Does coercion allow me to assign values to primitives?

    Yes. The primitive is wrapped in an object, and a property is created on that. No exception will be thrown.

    why adding properties to it results to undefined?

    The adding itself does result in the value.

    var str = "abc";
    console.log(str.someProperty = 5); // 5
    

    Yet, what you're asking for is getting a property from a primitive. This will return in undefined since the primitive is wrapped in a new wrapper object - not the one which you assigned the property on:

    console.log(str.someProperty); // undefined
    

    It only works for special properties like .length that are created with the object, or inherited ones like slice or charAt methods (see the docs for those).

    If you wanted such a thing, you'd need to create the wrapper object explicitly and store it somewhere:

    var strObj = new String("abc");
    strObj.someProperty = 5;
    console.log(strObj.someProperty); // 5
    // coercion and the `toString` method will even make the object act like a string
    console.log(strObj + "def"); // "abcdef"
    
    0 讨论(0)
提交回复
热议问题