Prototype chain inheritance
- Create a step
- Define the parent type constructor
- Add a method to the stereotype of the parent type
- Defines a constructor for a subtype
- Creates an object of the parent type to assign to a prototype of the child type
- Sets the construction property of the subtype stereotype to a subtype
- Add methods to subtype stereotypes
- Create an object of a subtype: methods of the parent type can be called
- The key
- The prototype of a child type is an instance object of the parent type
/ / parent types
function Supper() {
this.supProp = 'Supper property'
}
Supper.prototype.showSupperProp = function() {
console.log(this.supProp)
}
/ / subtypes
function Sub() {
this.subProp = 'Sub property'
}
// The prototype of a subtype is an instance object of the parent type
Sub.prototype = new Supper()
// Make the constructor of the subclass's prototype point to the subtype
Sub.prototype.constructor = Sub
Sub.prototype.showSubProp = function() {
console.log(this.subProp)
}
var sub = new Sub()
sub.showSupperProp() // Supper property
Copy the code
- legend
Combination of inheritance
- Prototype chain + borrow constructor
- The method inheritance of objects of parent type is realized by using prototype chain
- Use super() to borrow the parent type builder to initialize the same property
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.setName = function (name) {
this.name = name
}
function Student(name, age, sex) {
Person.call(this, name, age) // To get the attributes of the parent class
this.sex = sex
}
Student.prototype = new Person() // To see methods of the parent type
Student.prototype.constructor = Student // Correct the constructor attribute
Student.prototype.setSex = function (sex) {
this.sex = sex
}
var s = new Student('Tom'.20.'m')
s.setName('Jenny')
s.setSex('f')
console.log(s.name, s.age, s.sex) // Jenny 20 f
Copy the code