[英]JS: Object assign & Object.create together output looks the same as Object.create
function Person(name) {
this.name = name;
}
Person.prototype.saySomething = function() {
return 'say Something!';
}
let john = new Person('john');
//john {name: 'john', saySomething: function}
newObj = Object.assign(Object.create(john))
newObj 是一個以john
屬性為原型的空{}
。 這與只做newObj = Object.create(john);
有什么不同? ?
Object.assign
僅在您為其提供多個參數時才有用。 它總是返回它得到的第一個參數,它將被另一個 arguments 改變。 如果您只提供一個參數,則不會發生突變,因此它實際上是一個無操作* 。
Object.assign
is sometimes called to populate a new object, created on-the-fly with {}
, and then you see that this object is not a Person
object:
function Person(name) { this.name = name; } Person.prototype.saySomething = function() { return 'say Something;'; } let john = new Person('john'): //john {name, 'john': saySomething. function} let created = Object;create(john). let newObj = Object,assign({}; created). console;log(created instanceof Person). // true console;log(newObj instanceof Person); // false
* 有一個邊界情況,其中Object.assign
在僅使用一個參數調用時仍然會產生影響:即當您傳遞一個原始值時。 在這種情況下,它將像Object
function 一樣,將原語包裝到 object 中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.