zoukankan      html  css  js  c++  java
  • JavaScript Patterns 3.1 Object Literal

    Basic concept

    Values can be

    properties: primitives or other objects

    methods: functions

    User-defined native objects are mutable at any time.  

    Object literal notation is ideal for this type of on-demand object creation.  

    Even the simplest {} object already has properties and methods inherited from Object.prototype.

    var dog = {
        name: "Benji",
        getName: function () {
            return this.name;
        }
    }; 
    1. The Object Literal Syntax

      • Wrap the object in curly braces ({ and }).

      • Comma-delimit the properties and methods inside the object. A trailing comma after the last name-value pair is allowed but produces errors in IE, so don't use it.

      • Separate property names and property values with a colon.

      • When you assign the object to a variable, don't forget the semicolon after the closing }.

    2. Objects from a Constructor
      // one way -- using a literal
      
      var car = {goes: "far"};
      
      // another way -- using a built-in constructor
      
      // warning: this is an antipattern
      
      var car = new Object();
      
      car.goes = "far";
    3. Object Constructor Catch

      Don't use new Object(); use the simpler and reliable object literal instead.

      // Warning: antipatterns ahead
      
      // an empty object
      
      var o = new Object();
      
      console.log(o.constructor === Object); // true
      
      // a number object
      
      var o = new Object(1);
      
      console.log(o.constructor === Number); // true
      
      console.log(o.toFixed(2)); // "1.00"
      
      // a string object
      
      var o = new Object("I am a string");
      
      console.log(o.constructor === String); // true
      
      // normal objects don't have a substring()
      
      // method but string objects do
      
      console.log(typeof o.substring); // "function"
      
      // a boolean object
      
      var o = new Object(true);
      
      console.log(o.constructor === Boolean); // true
  • 相关阅读:
    Java进阶学习(5)之设计原则(下)
    Java进阶学习(5)之设计原则(上)
    Java进阶学习(4)之继承与多态(下)
    Java进阶学习(4)之继承与多态(上)
    Java进阶学习(4)之继承与多态.demo
    python自动更新升级失败解决方案
    信息检索
    对卷积神经网络原理理解
    对DensePose: Dense Human Pose Estimation In The Wild的理解
    Java进阶学习(3)之对象容器.小练习
  • 原文地址:https://www.cnblogs.com/haokaibo/p/Object-Literal.html
Copyright © 2011-2022 走看看