Javascript assigning value to primitive

后端 未结 2 540
情话喂你
情话喂你 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.

提交回复
热议问题