我觉得差已经点击了我的头,但我只是想确信的差异。在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