Object.assign()
Object.assign()
這個方法是用于拷貝JSON對象的,複制對象的可枚舉屬性。
target
是目标對象,
source
是原對象,傳回目标對象。
看例子:
let returnedValue = Object.assign({ a: 1, b: 2 }, { c: 4, d: 5 });
console.log(returnedValue);
returnedValue = Object.assign({}, { e: 6, f: 7 });
console.log(returnedValue);
輸出:
> Object { a: 1, b: 2, c: 4, d: 5 }
> Object { e: 6, f: 7 }
再看個例子:
const target = {};
const source = { a: 1, b: 2 };
const returnedTarget = Object.assign(target, source);
console.log('target = ', target);
console.log('returnedTarget = ', returnedTarget);
輸出:
> "target = " Object { a: 1, b: 2 }
> "returnedTarget = " Object { a: 1, b: 2 }
根據結果可以感受一下。
Object.create()
Object.create()
建立新的對象,用法:
proto
是新建立對象的原型,傳回一個新建立的對象,并且帶有指定的原型對象和屬性。
const student = {
name: null,
age: -1,
printInfo: function () {
console.log(`Hello ${this.name}, your age is ${this.age}.`);
}
};
const stu1 = Object.create(student);
console.log(stu1);
stu1.name = "Tom";
stu1.age = 22;
stu1.printInfo();
輸出:
> Object { }
> "Hello Tom, your age is 22."