Object 的使用

Object 是构造函数 , 同时作为所有对象的父级.它的原型中很对对象操作的很多方法值得深究.

趁此次复习,现将所有函数的作用简单罗列,带日后再慢慢丰富这篇文章的羽翼.

Object.assign()
  通过浅复制一个或多个对象来创建一个新的对象。功能类似 $.extend

Object.create( prototype )

  根据传入的 原型对象 来创造一个新对象,可以借此来实现集成. 

 

// Shape - superclass
function Shape() {
  this.x = 0;
  this.y = 0;
}

// superclass method
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

console.log('Is rect an instance of Rectangle?',
  rect instanceof Rectangle); // true
console.log('Is rect an instance of Shape?',
  rect instanceof Shape); // true
rect.move(1, 1); // Outputs, 'Shape moved.'

Object.defineProperty( obj, 属性,{

  // 是否可枚举 是否会被  for…in 循环到

  enumerable: false,

  // 为true时,属性可以改变,也可以删除

  configurable: false,

  // 是否可以更改

  writable: false,

  // 值
  value: "static"

  // set ,get 与 writable,value 不可同时出现

  // 有 set 或 get 则为存取描述符 ,否则为 数据描述符

  get : function(){
    return bValue;
  },
  set : function(newValue){
    bValue = newValue;
  }

} )

var o = {};

o.a = 1;
// 等同于 :
Object.defineProperty(o, "a", {
  value : 1,
  writable : true,
  configurable : true,
  enumerable : true
});


// 另一方面,
Object.defineProperty(o, "a", { value : 1 });
// 等同于 :
Object.defineProperty(o, "a", {
  value : 1,
  writable : false,
  configurable : false,
  enumerable : false
});

Object.definedProperties( obj ,prop )

  功能同上,不同之处是在可以同时修改多个属性

var obj = {};
Object.defineProperties(obj, {
  'property1': {
    value: true,
    writable: true
  },
  'property2': {
    value: 'Hello',
    writable: false
  }
});

Object.freeze( obj )

  将 obj 的属性冻结,无法修改, 只是浅冻结, 不影响属性对象的属性修改

Object.is( value1 , value2 )

判断规则:

  Object.is() 判断两个值是否相同。如果下列任何一项成立,则两个值相同:

两个值都是 undefined
两个值都是 null
两个值都是 true 或者都是 false
两个值是由相同个数的字符按照相同的顺序组成的字符串
两个值指向同一个对象
两个值都是数字并且
都是正零 +0
都是负零 -0
都是 NaN
都是除零和 NaN 外的其它同一个数字

Object.seal( obj )

  将 obj 密封,不可以添加新属性,属性不可删除

原文地址:https://www.cnblogs.com/xiaxiaodong/p/8280616.html