首页 > 网站 > WEB开发 > 正文

JavaScript Patterns 3.1 Object Literal

2024-04-27 14:23:31
字体:
来源:转载
供稿:网友

javaScript Patterns 3.1 Object Literal

2014-05-27 12:30 by 小郝(Kaibo Hao), ... 阅读, ... 评论, 收藏, 编辑

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 literalvar car = {goes: "far"};// another way -- using a built-in constructor// warning: this is an antipatternvar 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 objectvar o = new Object();console.log(o.constructor === Object); // true// a number objectvar o = new Object(1);console.log(o.constructor === Number); // trueconsole.log(o.toFixed(2)); // "1.00"// a string objectvar o = new Object("I am a string");console.log(o.constructor === String); // true// normal objects don't have a substring()// method but string objects doconsole.log(typeof o.substring); // "function"// a boolean objectvar o = new Object(true);console.log(o.constructor === Boolean); // true

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表