Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ใน JavaScript Inheritance: แยกความแตกต่างระหว่าง Object.create() และ new

ทั้งสองวิธีทำงานต่างกันอย่างสิ้นเชิง:

1. Object.create() - สืบทอด prototype เท่านั้น:

function SomeClass() { }
SomeClass.prototype = Object.create(amitBaseClass.prototype);

สร้าง prototype chain ใหม่ ไม่เรียก constructor ของ parent

2. new - เรียก constructor และสืบทอด instance ทั้งหมด:

function SomeClass() { }
SomeClass.prototype = new amitBaseClass();

สร้าง instance ของ parent class จริงๆ แล้ว assign ให้ prototype

สรุป: Object.create() เบากว่า ไม่เรียก constructor parent ส่วน new เรียก constructor และ copy own properties ด้วย