原文 http://javascriptissexy.com/javascript-objects-in-detail/
JavaScript核心最常用和最基础的数据类型是Object数据类型。JavaScript拥有一个复杂数据类型Object数据类型和五种简单数据类型Number,Boolean,Undefined,Null。这些简单数据类型是不可变的,但对象是可变的。
对象的概念
对象是原始数据类型(有时候是引用类型)的无序列表,其以name-value键值对方式存储。列表中每一项被称作属性(函数被称为方法),每个属性的名字唯一可以是字符串或数字。
引用数据类型和原始数据类型
引用数据类型以引用方式存储数据,不是直接存储变量值本身
原始数据类型直接存储变量本身
// The primitive data type String is stored as a value
var person = "Kobe";
var anotherPerson = person; // anotherPerson = the value of person
person = "Bryant"; // value of person changed
console.log(anotherPerson); // Kobe
console.log(person); // Bryant
//reference data type
var person = {name: "Kobe"};
var anotherPerson = person;
person.name = "Bryant";
console.log(anotherPerson.name); // Bryant
console.log(person.name); // Bryant
对象成员的属性
对象中的每个成员不仅仅有key-value组成的键值对,而且有3个属性默认设置为true
• Configurable Attribute(可配置属性):成员是否可删除或修改
• Enumerable(可枚举):成员是否可以用于for/in循环
• Writable(可写):成员是否可写
创建对象
• Object Literals (字面量创建对象)
•Object Construct(构造器方式)
•Prototype Pattern for Creating Objects
自有属性和继承属性
自有属性定义在对象中,继承属性继承自对象原型prototype中的属性。
自有属性和继承属性通过in操作符判断,自有属性可以通过对象的hasOwnProperties方法判断
// Create a new school object with a property name schoolName
var school = {schoolName:"MIT"};
// Prints true because schoolName is an own property on the school object
console.log("schoolName" in school); // true
//Prints false because we did not define a schoolType property on the school object, and
//neither did the object inherit a schoolType property from its prototype object.
console.log("schoolType" in school); // false
// Prints true because the school object inherited the toString method from Object.prototype.
console.log("toString" in school); // true
// Prints true because schoolName is an own property on the school object
console.log(school.hasOwnProperty ("schoolName")); // true
// Prints false because the school object inherited the toString method from Object.prototype,
//therefore toString is not an own property of the school object.
console.log(school.hasOwnProperty ("toString")); // false
继承自Object.prototype属性不可枚举,不能使用for/in循环输出,对象本身通过Prototype关联的属性可以输出。
删除对象的属性
利用delete操作符删除对象的属性,不能删除继承过来的属性,delete操作符总是返回true。
var christmasList = {mike:"Book", jason:"sweater" }
delete christmasList.mike; // deletes the mike property
for (var people in christmasList) {
console.log(people);
}
// Prints only jason
// The mike property was deleted
delete christmasList.toString; //returns true,but toString not deleted because inherited method
// Here we call the toString method and it works just fine—wasn’t deleted
christmasList.toString(); //"[object Object]"