继 html
(译)ECMAScript 5 Objects and Properties web
全文地址 http://ejohn.org/blog/ecmascript-5-objects-and-properties/数组
@by Aaronecmascript
新功能this
新增长一些有趣的新特性已经被引入到语言google
如下两个方法是很是有用的,用于收集全部的属性的数组对象。url
Object.keys( obj )
spa
将会返回一个字符串格式的数组表示全部可枚举的对象属性名,相同方法的一个实现prototype
代码实现:code
Object.keys = function( obj ) { var array = new Array(); for ( var prop in obj ) { if ( obj.hasOwnProperty( prop ) ) { array.push( prop ); } } return array; };
示例用法:
var obj = { name: "John", url: "http://ejohn.org/" }; print( Object.keys(obj).join(", ") ); // name, url
Object.getOwnPropertyNames( obj )
几乎全部用Objet.keys返回对象的全部属性名(不仅是可枚举的的)
Object.create( proto, props )
建立一个新对象的原型是等于值的原型并经过对象的属性设置 Object.defineProperties( props )
.
示例实现
Object.create = function( proto, props ) { var ctor = function( ps ) { if ( ps ) Object.defineProperties( this, ps ); }; ctor.prototype = proto; return new ctor( props ); };
另外的实现:
Object.create = function( proto, props ) { var obj = new Object(); obj.__proto__ = proto; if ( typeof props !== "undefined" ) { Object.defineProperties( obj, props ); } return obj; };
说明:
以上代码能够用mozilla特定原型属性,这个属性容许您访问一个对象的内部原型-而且容许你设置它的值,一样,ECMA5的方法Object.getPrototypeOf也容许你访问这个值,可是不能过设置这个值-所以上述方法不能实现一个通用的、规范兼容的方式
示例用法:
function User(){} User.prototype.name = "Anonymous"; User.prototype.url = "http://google.com/"; var john = Object.create(new User(), { name: { value: "John", writable: false }, url: { value: "http://google.com/" } }); print( john.name ); // John john.name = "Ted"; // Exception if in strict mode
Object.seal( obj )
Object.isSealed( obj )