Original Address
## Foreword
Jun watermelon before learning the basics of the JS and the three big mountains, but not how to use the work after the impression is not deep, this time intend to re-learn it, and lay a solid foundation. Red duck ~ ~
Prototype mode
JS inheritance is achieved by way of the prototype and the prototype chain, JS no class (referred to herein ES5, ES6 are combined with a class of syntactic sugar)
Each function has the prototype (prototype) property, which is a pointer to an object, the use of this object is shared by all instances of the properties and methods of a particular type, i.e., the prototype object is used to share properties and Examples method.
And in each instance has a pointer to the prototype object ( proto ).
5 prototype rules
- All reference types (array, object, function), have object properties, and can be freely extended attributes
举个栗子
var obj = {
name:'波妞'
}
console.log(obj) // { name: '波妞' }
obj.like = '宗介'
console.log(obj) // { name: '波妞', like: '宗介' }
- ** All reference type has a __proto__ property, the property value is a normal object **
- All functions have a prototype property, the property value is a normal object
- ** All reference type attribute value of prototype points __proto__ its constructor **
- ** When trying to get a property of an object, if the object itself does not have this property, then he will go to its __proto __ (that is, its prototype constructor) to find **
Prototype chain
Understood that: Each type has a reference __proto__, each has a function prototype, the prototype reference type __proto__ its constructor point to the same object; the reference type is invoked, if the method does not in itself calls or attributes , will go __proto __ (that is, its prototype constructor) find no words will continue to look for __proto__ prototype, the prototype pointing to the top Object null date
function Foo (name, age) {
this.name = name
}
Foo.prototype.print = function () {
console.log(this.name)
}
var f = new Foo('波妞')
f.print() // 波妞
Prototype chain to inherit a small chestnut
function Elem(id) {
this.elem = document.getElementById(id)
}
Elem.prototype.html = function (val) {
var elem = this.elem
if (val) {
elem.innerHTML = val
return this // 链式编程
}else{
return elem.innerHTML
}
}
Elem.prototype.on = function (type, fn) {
var elem = this.elem
elem.addEventListener(type, fn)
}
var div1 = new Elem('div1')
console.log(div1. html())
If wrong, please correct me
the above