一、JavaScript没有类的概念。
对象就是一组key-value对,其中,value可以是数据或者对象。
对象的创建或者初始化有两种方法:
1. 使用 new 关键字,通过构造函数生成对象:
var o = new Object();
然后就可以给对象 o 添加各种属性和函数。其中,Object是一个构造函数。
所谓构造函数,就是一个一般的函数。也可以自定义构造函数(首字母要大写):
function Student(){
this.name = 'Jerry';
this.age = 12;
this.sex = 'man';
}
var student1 = new Student();
2. 使用对象字面量方式:
var o = {
name : 'Jerry',
age : 12,
sex : 'man'
};
所有对象都继承自Object对象,Object对象有自己的属性和函数。
二、任何对象创建后,都会有一个内部指针,指向一个原型对象。原型对象存在的意义就是属性和函数共享。举例说明:
一般方式:
function Student(){
this.name = 'Jerry';
this.age = 12;
this.sex = 'man';
}
var student1 = new Student();
var student2 = new Student();
student2.name = 'Tom';
console.log(student1.name); // 'Jerry'
console.log(student2.name); // 'Tom'
原型方式:
function Student(){
this.name = 'Jerry';
this.age = 12;
this.sex = 'man';
};
Student.prototype.lastname = 'TomAndJerry';
var student1 = new Student();
var student2 = new Student();
student2.name = 'Tom';
console.log(student1.name); //'Jerry'
console.log(student1.lastname); //'TomAndJerry'
console.log(student2.name); //'Tom'
console.log(student2.lastname);//'TomAndJerry'
student1.lastname = 'JiaFeiMao'
console.log(student1.name); //'Jerry'
console.log(student1.lastname); //'JiaFeiMao'
console.log(student2.name); //'Tom'
console.log(student2.lastname);//'JiaFeiMao'
三、属性的特性
对象中每个属性都有特性,一般属性包含下列四种特性:
[[Configurable]] 表示该属性不能使用delete操作符删除
[[Enumerable]] 表示该属性能否通过for-in循环返回
[[Writable]] 表示该属性是否可写
[[Value]] 表示该属性的值
修改属性的特性使用 Object.definePropetry 函数
var student = {};
student.name = 'Tom';
var descriptor = Object.defineProperty(student, 'name', {
Configurable = true,
Enumerable = true,
Writable = true;
value = 'Jerry';
});
console.log(student.name);
对象的属性中有一种特殊的属性,名为“访问器属性”,它没有数值,但包含一对setter和getter函数,它有一下四个特性:
[[Configurable]] 同上;
[[Enumerable]] 同上;
[[Get]] 读取属性时调用的函数;
[[Set]] 设置属性时调用的函数。
例如:
var book = {
_year : 2004,
edition : 1
};
Object.defineProperty(book, 'year', {
get : function(){
return this._year;
},
set : function(newValue){
if (newValue > 2004){
this._year = newValue;
this.edition += newValue - 2004;
}
}
});
book.year = 2006;
console.log(book.edition);
//指定要set函数,意味着只能写,不能读;只定义get函数,意味着只能读,不能写。
也可以使用 Object.definePropertites 批量定义属性的特性
var book = {
_year : 2004,
edition : 1
};
Object.definePropertites(book, {
_year : {
value : 2004
},
edition : {
value : 1
},
year : {
set : function(){
return this._year;
},
get : function(newValue){
if (newValue > 2004){
this._year = newValue;
this.edition += newValue - 2004;
}
}
}
});
读取属性的特性,用 Object.getOwnPropertyDescriptor
var book = {
_year : 2004,
edition : 1
};
var descriptor = Obejct.getOwnPropertyDescriptor(book, '_year');
console.log(descriptor.Configurable);
console.log(descriptor.Enumerable);
console.log(descriptor.Writable);
console.log(descriptor.Value);