Everything is an object?

前端 未结 5 1478
南笙
南笙 2020-12-18 14:49

At one popular blog, the author asked his audience what was their “Ah ha!” moment for JavaScript and most of the people said that it was realizing that everything in JavaScr

5条回答
  •  春和景丽
    2020-12-18 15:29

    What they mean, most likely, is that any data that can be assigned to a variable has properties (and therefore methods) that can be accessed in an object like fashion.

    // strings
    "asdf".length;              // 4
    "asdf".replace('f', 'zxc'); // "azxc"
    
    // numbers
    (10).toFixed(2);            // "10.00"
    
    // booleans
    true.someProp;              // undefined (point is it doesn't crash)
    

    They even have prototypes they inherit from.

    "omg".constructor;          // function String() { [native code] }
    String.prototype.snazzify = function() {
      return "*!*!*" + this + "*!*!*";
    };
    
    "omg".snazzify();           // "*!*!*omg*!*!*"
    

    However, these are primitives, and while they behave object like in a lot of ways, they are different from other "real" JS objects in a few ways. The biggest of which is that they are immutable.

    var s = "qwerty";
    s.foo;              // undefined, but does not crash
    s.foo = 'some val'; // try to add a property to the string
    s.foo;              // still undefined, you cannot modify a primitive
    

    Do note though that functions are real mutable objects.

    var fn = function(){};
    fn.foo;              // undefined
    fn.foo = 'some val'; // try to add a property to the function
    fn.foo;              // "some val"
    

    So while it's not technically true that "everything in JS is an object", under most circumstances you can treat them mostly like objects in that they have properties and methods, and can potentially be extended. Just be sure you understand the caveats.

提交回复
热议问题