【发布时间】:2014-06-02 23:05:46
【问题描述】:
以下是一些示例,展示了基于对象定义和创建方式的原型继承的不同行为。我区分对象的“原型属性”,例如someObject.prototype 和“原型引用”(我认为应该引用 someObject 继承的对象?)。
示例 1
这似乎是保留父对象的原型属性的方法。这不是推荐的继承方式吗?
// create object whose prototype reference is Object; add stuff.
var Parent = Object.create(Object);
Parent.a = "1";
Parent.f = function() { return true; };
// add stuff to prototype property
Parent.prototype.b = 1;
Parent.prototype.g = function() { return false; };
// create an object whose prototype reference is Parent (??)
var Child = Object.create(Parent);
console.log(Parent.__proto__) // [Function: Object]
console.log(Parent.prototype) // { b: 1, g: [Function] }
console.log(Child.__proto__) // { a: '1', f: [Function] }
console.log(Child.prototype) // { b: 1, g: [Function] }
我本来希望
Child.__proto__以同样的方式命名Parent命名Parent.__proto__命名Object。我们看到
Child的原型引用指向Parent的属性,而不是Parent.prototype的属性。这至少对我来说是违反直觉的,因为我本来希望看到Parent.prototype的属性b和g代替。
示例 2
混合结果。
// use a constructor instead.
var Parent = function () {
this.a = "1";
this.f = function() { return true; };
}
// again, add stuff to prototype property.
Parent.prototype.b = 1;
Parent.prototype.g = function() { return false; };
// create an object whose prototype reference is Parent (??)
var Child = new Parent();
// create differently
var Sibling = Object.create(Parent);
console.log(Parent.__proto__) // [Function: Empty]
console.log(Parent.prototype) // { b: 1, g: [Function] }
console.log(Child.__proto__) // { b: 1, g: [Function] }
console.log(Child.prototype) // undefined
console.log(Sibling.__proto__) // [Function]
console.log(Sibling.prototype) // { b: 1, g: [Function] }
这里,
Child的原型引用了Parents.prototype的属性。这就是我的预期?另一方面,
Sibling的原型引用现在是一个函数,即Parent的原型引用。
示例 3
这似乎是保留父对象的原型引用的方法,但是您丢失了它的原型属性。
// create object constructor; add stuff.
var Parent = function () {
this.a = "1";
this.f = function() { return true; };
}
// add stuff to prototype property.
Parent.prototype.b = 1;
Parent.prototype.g = function() { return false; };
// create an object whose prototype reference is Parent (??)
var Child = function() {
this.c = "2";
};
// supposed Ad-hoc prototype inheritance
Child.prototype = Object.create(Parent.prototype)
console.log(Parent.__proto__) // [Function: Empty]
console.log(Parent.prototype) // { b: 1, g: [Function] }
console.log(Child.__proto__) // [Function: Empty]
console.log(Child.prototype) // {}
示例 1 中显示的方法是否首选,因为您可以访问父级的原型属性、它自己的属性以及 Object 的属性/方法?我在其他帖子中读到,其中一些继承方式应该是平等的……这是不正确的。另外,我读过其他帖子,例如here,示例 3 是要走的路。或者我只是不确定__proto__ 代表什么......
感谢您对这些混搭情况之间的差异的任何澄清!
【问题讨论】:
-
关于你的标题:没有
__prototype__:-) -
很好的问题,特别是对于低代表用户。 (票数用完了,所以不能 +1)
-
@Bergi 哈哈谢谢,我已经更正了。
标签: javascript inheritance prototype