js 创建对象1

创建对象

1.对象直接量(最简单的创建对象的方式)

  The easiest way to create an object is to include an object literal in your JavaScript code. An object literal is a comma-separated list of property name/value pairs, enclosed within curly braces. Each property name can be a JavaScript identifier or a string(标识符和字符串都可以用作属性名), and each property value can be a constant or any JavaScript expression(常量和表达式都可做属性值).

 

var empty = {};  // An object with no properties
var point = { x:0, y:0 };                                             //标识符作为属性名
var circle = { x:point.x, y:point.y+1, radius:2 };
var homer = {
    "name": "Homer Simpson",                                      // 字符串作为属性名
    "age": 34,
    "married": true,
    "occupation": "plant operator",
    'email': homer@example.com
};

 

An object literal is an expression that creates and initializes a new and distinct object each time it is evaluated. That is, a single object literal can create many new objects if it appears within the body of a loop in a function that is called repeatedly.(对象直接量是一个每次都会创建和初始化一个新的不同的对象的表达式,"好像不通:不知道要怎么翻译了")

 

 2.new 操作符来创建对象

 The new operator can create specialized kinds of objects. You follow it with an invocation of a constructor function that initializes the properties of the object. (new操作符后是一个 用于初始化对象属性的构造函数的引用)

 

var a = new Array();

var d = new Date();

var r = new RegExp("javascript", "i");

 

Array()、 Date()、 RegExp()是 javascript core 中预定义的一部分构造器,我们也可以定义 自定义的构造函数已任何想要的方式初始化新创建的对象。

 

Note:The Object() constructor creates an empty object, just as the literal {} does

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值