一:创建对象
1:直接创建
var empty={}; var point = {x:0,y:0}; var point2 = {x:point.x,y:point.y+1}; var book={ "main title":"Javascript", "sub-title":"The Definitive Guide", "for":"all audiences" }
2:通过new创建对象
var o = new Object(); var arr = new Array(); var time = new Date(); var r = new RegExp();
3:原型创建对象
function Person() { } Person.prototype.name = "zxj"; Person.prototype.age = 29; Person.prototype.job = "Software Engineer"; Person.prototype.sayName = function () { alert(this.name); } var person1 = new Person(); person1.sayName(); //zxj var person2 = new Person(); person2.sayName(); //zxj
二:访问:
通过(.)和[]来获取属性的值。(.)左侧必须是一个以属性名称命名的简单标识符,[],方括号必须是一个计算结果为字符串的表达式,这个字符串就是属性的名字。
var author = book.author; var name = author.surname; var title = book["name title"]