Javascript 中继承对象的两种不同(?)方法
Javascript中以下两种继承对象的方法有什么区别吗?
function Person(name) {
this.name = name;
}
function Student(name, id) {
Person.call(this, name);
this.id = id;
}
方法1:
Student.prototype.__proto__ = Person.prototype;
方法2:
Student.prototype = new Person;
Student.prototype.constructor = Student;
Is there any difference between the following two methods of inheriting objects in Javascript?
function Person(name) {
this.name = name;
}
function Student(name, id) {
Person.call(this, name);
this.id = id;
}
Method 1:
Student.prototype.__proto__ = Person.prototype;
Method 2:
Student.prototype = new Person;
Student.prototype.constructor = Student;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除了按指定模式创建对象之外,构造函数还做了另一件有用的事情,它自动为新创建的对象设置原型对象。该原型对象存储在
ConstructorFunction.prototype
属性中。您可以通过将几乎“内部”的
.__proto__
属性设置为特定对象来显式地做到这一点。无论如何,这在所有 javascript 实现中都是不可能的。但基本上,它几乎是一样的。如果没有专门为对象设置原型,则采用默认对象(
Object.prototype
)。Besides creation of objects by specified pattern, a constructor function does another useful thing, it automatically sets a prototype object for newly created objects. This prototype object is stored in the
ConstructorFunction.prototype
property.You can explicitly do that by setting the, pretty much "internal",
.__proto__
property to a specific object. That is not possible in all javascript implementations anyway. But basically, its pretty much the same.If the prototype is not set specifically for an object, the default object is taken (
Object.prototype
).