NoteDeep

Object是什么?


The Object constructor creates an object wrapper for the given value.
If the value is null or undefined, it will create and return an empty object,
otherwise, it will return an object of a Type that corresponds(对应的) to the given value.
If the value is an object already, it will return the value.

Object constructor 是一个构造函数。

new 操作符具体做了哪些事情呢?

The new operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

Object类具有的属性和方法

属性:
  • Constructor: 创建对象的函数。对于Object类,该指针指向原始的object()函数。
  • Prototype: 对象的原型对象。

方法:
  • hasOwnProperty(property): 判断对象是否有某个特定的属性。须是来自对象本身的属性,来自原型的属性不算
  • isPrototypeOf(object): 判断该对象是否为另一个对象的原型。
  • propertyIsEnumerable(property): 判断给定的属性是否可以用for…in语句进行枚举。
  • toString(): 返回对象的原始字符串表示。
  • valueOf(): 返回对象的字符串、数值或布尔值表示。通常与toString()的返回值相同。

对象的属性

数据属性
访问器属性

A、数据属性:包含一个数据值的位置,在这个位置可以读取和写入值,有4个描述其行为的特性

  • [[Configurable]]:表示能否通过delete删除属性从而重新定义属性,能否修改属性的特性,或者能否把属性修改为访问器属性,默认值为true
  • [[Enumberable]]:表示能否通过for-in循环返回属性,默认值为true
  • [[Wtiteable]]:表示能否修改属性的值,默认值为true
  • [[Value]]:包含这个属性的数据值,读取属性值/写入属性值,从这个位置读/把新值保存在这个位置,默认值为undefined

var person={};
Object.defineProperty(person,'name',{
writeable:false,
value:'t'
});
console.log(person.name);
person.name='q';
console.log(person.name); //在非严格模式下复制操作被忽略,严格模式下报错


一旦将configurable特性设置为false之后就不能改回来了。
defineproperty函数中:configurable、writeable、enumberable的默认值都是false。

var person={};
Object.defineProperty(person,'name',{
configurable:false,
value:'t'
});
console.log(person.name); //t
delete person.name;
console.log(person.name); //非严格模式显示t,严格模式致错


B、访问器属性
访问器属性不包含数据值,它们包含一对getter和setter函数。

特性:
  • [[configurable]]:表示能否通过delete删除属性从而重新定义属性,能否修改属性的特性,或者能否把属性修改为访问器属性,默认值为true
  • [[Enumberable]]:表示能否通过for-in循环返回属性,默认值为true
  • [[Get]]:在读取属性时调用的函数,默认值为undefined
  • [[Set]]:在写入属性时调用的函数,默认值为undefined
访问器属性不能直接定义,必须使用Object.defineProperty()
var book={
_year:2017, //下划线是常用的标记,表示只能通过对象的方法访问的属性
edition:0
};
Object.defineProperty(book,'year',{
get:function(){
return this._year;
},
set:function(newValue){
if(newValue>2017){
this._year=newValue;
this.edition+=newValue-2017;
}
}
});
book.year=2020;
console.log(book.edition); //3

C、定义多个属性

ECMAScript5定义了Object.defineProperties()方法,用法如下:
var book={};
Object.defineProperties(book,{
_year:{
writeable:true,
value:2017
},
edition:{
writeable:true,
value:1
},
year:{
get:function(){
return this._year;
},
set:function(){
if(newValue>2017){
this._year=newValue;
this.edition+=newValue-2017;
}
}
}
});

D、读取属性的特性:Object.getOwnPropertyDescriptor()

如上例,
数据属性_year.value等于最初的值,configurable是false,get是undefined
访问器属性year.value等于undefined,enumberable是false,get是一个指向函数的指针
var descriptor = Object.getOwnPropertyDescriptor(book,"_year");


评论列表

    Object是什么?
    new 操作符具体做了哪些事情呢?
    Object类具有的属性和方法
    对象的属性