clone 是 JavaScript 裡很常被提到的一個技巧:不建立類,直接以一個現成物件作為原型,製造出新的物件。它很短,但行為上有幾個容易誤解的地方,值得實際跑一次看看。
<script type="text/javascript">
/* 克隆原型得到對象 */
function clone(object) {
function F() {}
F.prototype = object;
return new F;
}
var Person = {
name: 'default name',
getName: function () { return this.name; }
};
var reader = clone(Person);
console.log(reader.getName()); // 'default name'
reader.name = 'John Smith';
console.log(reader.getName()); // 'John Smith'
</script>
reader 本身沒有 name 屬性,第一次呼叫時它沿著原型鏈找到 Person 上的值;第二次指派之後,reader 有了自己的 name,於是遮蔽(shadow)掉了原型上的同名屬性。
<script type="text/javascript">
function clone(object) {
function F() {}
F.prototype = object;
return new F;
}
var Person = {
name: 'default name',
getName: function () { return this.name; }
};
/* Author 原型物件 */
var Author = clone(Person);
Author.books = []; // 書的陣列
Author.getBooks = function () { return this.books; };
var author = [];
author[0] = clone(Author);
author[0].name = 'Dustin Diaz';
author[0].books = ['JavaScript Design Patterns'];
author[1] = clone(Author);
author[1].name = 'Ross Harmes';
author[1].books = ['JavaScript Design Patterns', 'PHP', 'Mysql'];
console.log(author[0].getName());
console.log(author[0].getBooks());
console.log(author[1].getName());
console.log(author[1].getBooks());
</script>
結果:

順帶一提,這裡用 console.log 比 alert 有意思多了——alert 一次只能看一筆,陣列與物件還會顯示成 [object Object],而 console 能展開完整的結構。
<script type="text/javascript">
function clone(object) {
function F() {}
F.prototype = object;
return new F;
}
var Person = {
name: 'default name',
getName: function () { return this.name; }
};
var Author = clone(Person);
Author.books = [];
Author.getBooks = function () { return this.books; };
var authorClone = clone(Author);
console.log(authorClone.name); // 'default name'(沿原型鏈往上找到 Person)
authorClone.name = 'new name'; // 此時才在 authorClone 上建立自己的屬性
console.log(authorClone.name); // 'new name'
console.log(Author.getName()); // 仍是 'default name',沒有被影響
console.log(Author.getBooks()); // 空陣列
authorClone.books.push('new book'); // Author 被改到了!
authorClone.books.push('new new book');
console.log(Author.getBooks()); // ['new book', 'new new book']
console.log(authorClone.getBooks()); // 同上
authorClone.books = []; // 這一刻才擁有屬於自己的 books
authorClone.books.push('new book2');
authorClone.books.push('new book3');
authorClone.books.push('new book4');
console.log(authorClone.getBooks());
console.log(Author.getBooks());
var CompoundObject = {
string1: 'default value',
childObject: { bool: true, num: 10 },
getChild: function () { return this.childObject; }
};
var compoundObjectClone = clone(CompoundObject);
compoundObjectClone.childObject.num = 5; // 不好的方式:改到了原型上的物件
compoundObjectClone.childObject = { // 好一點的方式:整體替換
bool: true, num: 5
};
console.log(compoundObjectClone.getChild());
</script>
結果:

基本型值的指派是安全的,物件型值的修改不是。
authorClone.name = 'new name' 只是在 clone 自己身上新增一個屬性,原型的 name 完好如初。但 authorClone.books.push(...) 是「取得原型上的那個陣列,然後修改它」——因為 clone 自己身上還沒有 books,讀取時沿原型鏈拿到了共用參照,push 就改到了共用資料。要切開,必須用 authorClone.books = [] 這種整體指派,讓 clone 擁有自己的那一份。
同樣的道理出現在 childObject 上:compoundObjectClone.childObject.num = 5 會污染原型,而 compoundObjectClone.childObject = {...} 不會。
這其實就是原型式繼承最經典的坑,也是為什麼在 ES6 class 裡宣告「每個實例各自一份」的陣列屬性時,一定要寫在建構函式中(this.items = [])而不是寫在 prototype 上——寫在 prototype 上,所有實例會共用同一個陣列。
另外,這個 clone 是「淺複製」的:它複製的是原型鏈的參照,不是深拷貝。若需要真正獨立的一份資料,得用 structuredClone() 或 JSON.parse(JSON.stringify(obj))(後者會丟掉函式與 undefined)。
以上就是這篇的全部內容,希望對你的 JavaScript 開發有幫助。