我覺得差已經點擊了我的頭,但我只是想確信的差異。在Javascript中,間「的Object.create」和「新」
在道格拉斯克羅克福德Prototypal Inheritance in JavaScript頁,他說
在原型系統中,對象從對象繼承。但是,JavaScript, 缺少執行該操作的操作員。相反,它 有一個新的操作者,以使得新的f()的產生一個新的對象,該對象從f.prototype 繼承。
我真的不明白他想說的那句話,所以我進行了一些測試。在我看來,關鍵的區別是,如果我創建一個基於純原型系統的另一個對象的對象,那麼所有的父父成員應在新對象的原型,而不是新的對象本身。
這裏的測試:
var Person = function(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.toString = function(){return this.name + ', ' + this.age};
// The old way...
var jim = new Person("Jim",13);
for (n in jim) {
if (jim.hasOwnProperty(n)) {
console.log(n);
}
}
// This will output 'name' and 'age'.
// The pure way...
var tim = Object.create(new Person("Tim",14));
for (n in tim) {
if (tim.hasOwnProperty(n)) {
console.log(n);
}
}
// This will output nothing because all the members belong to the prototype.
// If I remove the hasOwnProperty check then 'name' and 'age' will be output.
我的理解是正確的,對象本身就爲大家測試時的區別僅變得明顯?
請參閱http://stackoverflow.com/questions/4166616/understanding-the-difference-between-object-create-and-new-somefunction-in-j – 2012-04-28 08:14:57
我昨天看過那個問題,我想,但是答案是我不清楚。現在,我已經完成我的測試,並輸入了我的問題,很明顯! – Jules 2012-04-28 08:21:16