ES6 之 对象扩展 前半部

属性的简介表示法

var foo = 'bar';
var baz = {foo};
console.log(baz);       //{ foo: 'bar' }


function f(x, y) {
    return {x, y};
}
console.log(f(1, 2));   //{ x: 1, y: 2 }


var o = {
    method() {
        return 'Hello';
    }
};
//等同于
var o = {
    method: function () {
        return 'Hello';
    }
};
console.log(o.method());        //Hello

function getPoint() {
    var x = 1;
    var y = 10;
    return {x,y};
}

console.log(getPoint());    //{ x: 1, y: 10 }


# CommJS模块输出变量就非常适合使用简介写法
var ms = {};

function getItem(key) {
    return key in ms ? ms[key] : null
}

function setItem(key, value) {
    ms[key] = value;
}

function clear() {
    ms = {}
}


module.exports = {getItem,setItem, clear};
//等同于
module.exports = {
    getItem:getItem(),
    setItem: setItem(),
    clear: clear()
}
ps: 以上属性的赋值器和取值器都采用了属性简写的方法

属性名表达式

JS语言定义对象的属性有两种方法。
1、用标识符定义属性(ES5)
2、用表达式作为属性名(ES6)

// ES5 标识符作属性名 
var obj = {
    foo:true,
    abc: 123
}

// ES6 表达式作为属性名

let propKey = 'foo';
let obj = {
    [propKey]: true,
    ['a'+'bc']:123
}

let lastWord = 'last word';
var a = {
    'first word':'hello',
    [lastWord]:'world'
}

console.log(a['first word']);
console.log(a[lastWord]);
console.log(a['last word']);

注意:属性名表达式和简介表示法不能同时使用

var foo = 'bar';
var bar = 'abc';
var baz = {[foo]};  //  绝壁报错

var foo = 'bar';
var baz = {[foo]: 'abc'};  // 正确写法

方法的name属性

var person = {
    sayName(){
        console.log(this.name);
    },
    get firstName(){
        return 'Loyal';
    }
}

console.log(person.sayName.name);       //亲测:sayName

console.log(person.firstName.name);     //亲测:undefined  书本答案为: get firstName

注意: 有两种特殊情况,1、bind方法创造的函数,name返回“bound”+原函数名字;2、Function构造函数创造的函数,name属性返回“anonymous”

console.log((new Function()).name);     //anonymous
var doSomething = function () {
        // ....
}
console.log(doSomething.bind().name);   //bound doSomething

Object.is() 用来比较两个值是否严格相等,它与严格比较运算符的欣慰基本一致


console.log(Object.is('foo', 'foo'));       //true
console.log(Object.is({}, {}));             //false

# 略有不同
console.log(+0 === -0);                     //true
console.log(NaN === NaN);                   //false

console.log(Object.is(+0, -0));             //false
console.log(Object.is(NaN, NaN));           //true

ps: ES5中可以使用以下代码来实现Object.is功能
Object.defineProperty(Object, 'is', {
    value: function(x,y){
       if(x === y) {
           return x !== 0 || 1/x === 1/y;
       }
        return x !== x && y !== y;
    },
    configurable: true,
    enumerable: false,
    writable: true
})

Object.assign() 用来将源对象的所有可枚举属性复制到目标对象,需要至少两个对象作为参数,第一个参数为目标对象,后面的参数为源对象,只要有一个不是对象,就会抛出TypeError错误

var target = {a: 11};
var source1 = {b:2};
var source2 = {c:3};
console.log(Object.assign(target, source1, source2));   //{ a: 11, b: 2, c: 3 }

# 注意,目标对象和源对象有同名属性,或多个源对象有同名属性,则后面属性会覆盖前面的属性
var target = {a: 11, b:3};
var source1 = {b:2};
var source2 = {c:3};
console.log(Object.assign(target, source1, source2));   //{ a: 11, b: 2, c: 3 }


# 嵌套的对象,Object.assign的处理方法是替换而不是添加
var target = {a:{b:{c:5,d:6}} };
var source1 = {a:{b:'hello'}};
console.log(Object.assign(target, source1));   //{ a: { b: 'hello' } }

# 处理数组,但会将其视为对象,进行替换
console.log(Object.assign([1, 2, 3], [4, 5]));  //[ 4, 5, 3 ]
  • 为对象添加属性

Class Point{
 constructor(x,y){
     Object.assign(this, {x,y})
 }
}
  • 为对象添加方法
Object.assign(SomeClass.prototype, {
  someMethod(arg1,arf2){

  },
  anotherMethod(){

  }
})
//等同于

SomeClass.prototype.someMethod = function (arg1,arf2){
  //...
}
SomeClass.prototype.anotherMethod = function () {
  //...
}
  • 克隆对象

function clone(origin){
    return Object.assign({}, origin);
}

以上将院士对象复制到一个控对象,就得到了运势对象的克隆
只能克隆原始对象自身的值,不能克隆他继承的值想要保持继承链,可以试用以下代码

function clone(origin) {
    let originProto = Object.getPrototypeOf(origin);
    return Object.assign(Object.create(originProto), origin);
}
  • 合并多个对象
const merge = (target,...source) => Object.assign(target,...source);
const merge = (...source) => Object.assign({}, ...source);
  • 为属性指定默认值
const DEFAUlTS = {
    logLEvel: 0,
    ouputFormat: 'html'
}
function processContent(options) {
    let options = Object.assign({}, DEFAUlTS, options);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章