Javascript中继承对象的两种不同方法
以下两种在Javascript中继承对象的方法有什么区别吗Javascript中继承对象的两种不同方法,javascript,inheritance,prototypal-inheritance,Javascript,Inheritance,Prototypal Inheritance,以下两种在Javascript中继承对象的方法有什么区别吗 function Person(name) { this.name = name; } function Student(name, id) { Person.call(this, name); this.id = id; } 方法1: Student.prototype.__proto__ = Person.prototype; Student.prototype = new Person; Student
function Person(name) {
this.name = name;
}
function Student(name, id) {
Person.call(this, name);
this.id = id;
}
方法1:
Student.prototype.__proto__ = Person.prototype;
Student.prototype = new Person;
Student.prototype.constructor = Student;
方法2:
Student.prototype.__proto__ = Person.prototype;
Student.prototype = new Person;
Student.prototype.constructor = Student;
除了通过指定的模式创建对象外,构造函数还做了另一件有用的事情,它自动为新创建的对象设置原型对象。此原型对象存储在
构造函数function.prototype
属性中
您可以通过将几乎是“内部”的\uuuu proto\uuuu
属性设置为特定对象来显式地实现这一点。无论如何,这在所有javascript实现中都是不可能的。但基本上,这几乎是一样的。
如果原型不是专门为某个对象设置的,那么将使用默认对象(
object.prototype
)。我认为设置构造函数
属性没有任何用处。