ES6允许直接写入变量和函数,作为对象的属性和方法。

var foo = 'bar';  
var baz = {foo};  
baz // {foo: "bar"}  

 

var fa = 'aa';
var mu = function(){
  console.log(1);
}
var bo = {fa,mu};
console.log(bo)  //VM2019:6 {fa: "aa", mu: ƒ} 

 

扩展:

Getters 和 setters

let obj = {
  get propName() {
    // getter, the code executed on getting obj.propName
  },

  set propName(value) {
    // setter, the code executed on setting obj.propName = value
  }
};

let user = {
  name: "John",
  surname: "Smith",

  get fullName() {
    return `${this.name} ${this.surname}`;
  },

  set fullName(value) {
    [this.name, this.surname] = value.split(" ");
  }
};

// set fullName is executed with the given value.
user.fullName = "Alice Cooper";

alert(user.name); // Alice
alert(user.surname); // Cooper

  

Javascript对象有两种属性,一种是数据属性,我们经常使用比较熟悉;第二种是访问器属性,本质就是获取和设置值的函数,但从代码上好像是正常属性

 

属性只能是访问器或数据属性,不能都是。如果我们视图给描述符同时提供getvalue,会报错:

// Error: Invalid property descriptor.
Object.defineProperty({}, 'prop', {
  get() {
    return 1
  },

  value: 2
});

  

Object.js
ES5比较两个值是否相等
Object.is('foo', 'foo')  
// true  
Object.is({}, {})  
// false  
+0 === -0 //true  
NaN === NaN // false  
  
Object.is(+0, -0) // false  
Object.is(NaN, NaN) // true  


Object.defineProperty(Object, 'is', {  
  value: function(x, y) {  
    if (x === y) {  
      // 针对+0 不等于 -0的情况  
      return x !== 0 || 1 / x === 1 / y;  
    }  
    // 针对NaN的情况  
    return x !== x && y !== y;  
  },  
  configurable: true,  
  enumerable: false,  
  writable: true  
});  


  1. function clone(origin) {  
  2.   let originProto = Object.getPrototypeOf(origin);  
  3.   return Object.assign(Object.create(originProto), origin);  
  4. }  

 

  1. const merge =  
  2.   (target, ...sources) => Object.assign(target, ...sources);  
const DEFAULTS = {
  log:1,
out:'html'
};
function proceeContent(option){
Object.assign({},DEFAULTS,options);
};




Object.assign()

Object.assign方法用于对象的合并,将源对象(source)的所有可枚举属性,复制到目标对象(target)

 

 

ES5有三个操作会忽略enumerablefalse的属性。

  • for...in循环:只遍历对象自身的和继承的可枚举的属性
  • Object.keys():返回对象自身的所有可枚举的属性的键名
  • JSON.stringify():只串行化对象自身的可枚举的属性
    • ES6新增了一个操作Object.assign(),会忽略enumerablefalse的属性,只拷贝对象自身的可枚举的属性。  

    • 这四个操作之中,只有for...in会返回继承的属性。实际上,引入enumerable的最初目的,就是让某些属性可以规避掉for...in操作。
posted on 2018-01-26 14:48  海米柚  阅读(102)  评论(0编辑  收藏  举报