Lay a solid foundation and fill in the gaps
It’s all about the basics
History of succession
1. Prototype chain inheritance
The prototype of the child constructor is equivalent to an object constructed by the parent that inherits too many useless attributes.Copy the code
Person.prototype.lastName = 'Keung'
function Person(name,age){
this.name = name
this.age = age
this.say = function (){
console.log(this.say)
}
}
var person = new Person('To'.24)
Student.prototype = person
function Student(name,age){}var student = new Student('To'.24)
Copy the code
Constructor inheritance
Borrow other constructors using call or applyCopy the code
Person.prototype.lastName = 'Keung'
function Person(name,age){
this.name = name
this.age = age
this.say = function (){
console.log(this.say)
}
}
var person = new Person('To'.24)
Student.prototype = person
function Student(name,age,grade){
Person.call(this,name,age)
this.grade = grade
}
var student = new Student('To'.24.100)
Copy the code
A chain of prototypes that cannot inherit borrowed functions calls the function one more time for each constructorCopy the code
Shared inheritance
If the child constructor wants to add an attribute to its prototype, the parent constructor prototype will also add an attribute. So let's do the fourth method.Copy the code
Person.prototype.lastName = 'Keung'
function Person(name,age){}var person = new Person('To'.24)
Student.prototype = Person.prototype
function Student(name,age,grade){}var student = new Student('To'.24.100)
Copy the code
Holy Grail mode
Prevent interaction on the prototype chain, but if you change the original properties of the prototype chain directly, you will still change the prototype of the parent constructor for reference value problems.Copy the code
Privatize variables with immediately executing functions and closuresvar inherit = (function(){
function F(){}
return function (target,orign){
F.prototype = orign.prototype
target.prototype = new F()
target.constructor = target // Otherwise target's constructor points to orign
target.uber = orign.prototype // Annotate who target inherits from
}
}())
Copy the code