(譯)ECMAScript 5 Objects and Properties (二)

繼  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 )

相關文章
相關標籤/搜索