adding properties to primitive data types other than Array

前端 未结 2 1866
闹比i
闹比i 2021-01-19 09:41

I\'m not supposed to add elements to an array like this:

var b   = [];
b.val_1 = \"a\";
b.val_2 = \"b\";
b.val_3 = \"c\";

I can\'t use nati

2条回答
  •  不知归路
    2021-01-19 09:50

    If an array is just an object in the same way a string or a number is an object,

    An array is different than strings, numbers, booleans, null and undefined. An array IS an object, while the others in the list are primitive values. You can add properties to the array just like you would with any other object, anything different being just what makes arrays special (the length property you mentioned for example). You cannot add properties or call methods on primitive values.

    In this previous answer i talked about the use of Object wrappers over primitive values. Feel free to read it to see more about Object wrappers. The following will be a very short example:

    console.log('TEST'.toLowerCase()) // 'test'
    

    While it may seem that the toLowerCase method is called on the string 'TEST', in fact the string is converted automatically to a String object and the toLowerCase method is called on the String object.

    Each time a property of the string, number or boolean is called, a new Object wrapper of the apropriate type is created to get or set that value (setting properties might be optimized away entirely by the browser, i am not sure about that).

    As per your example:

    var num    = 1; // primitive value
    num.prop_1 = "a string"; // num is converted to a Number, the prop_1 property is set on the Object which is discarded immediately afterwards
    console.log(num); //1 // primitive value
    console.log(num.prp);  // num is converted to a Number, which doesn't have the prp property
    

    My example:

    Number.prototype.myProp = "works!";
    String.prototype.myFunc = function() { return 'Test ' + this.valueOf() };
    Boolean.prototype.myTest = "Done";
    
    
    console.log(true.myTest); // 'Done'
    console.log('really works!'.myFunc()); // 'Test really works!'
    
    var x = 3;
    console.log(x.myProp.myFunc()); // 'Test works!'
    
    console.log(3['myProp']); // 'works!'
    

    On the other hand:

    console.log(3.myProp); // SyntaxError: Unexpected token ILLEGAL
    

    The number isn't necessarily treated differently, that syntax just confuses the parser. The following example should work:

    console.log(3.0.myProp); // 'works!'
    

提交回复
热议问题