1. Prototype
1. What is a prototype?
Prototype is the basis of inheritance in JS, and inheritance of JS is inheritance based on prototype.
2. Several basic definitions
(1) Each function has a prototype attribute, which by default points to an empty Object object (called the prototype object)
(2) There is a constructor attribute in the prototype object, which points to the function object
Code display:
(3) Graphic:
Note: The function name is Type, prototype is its attribute, Type.prototype points to the prototype object of Type, and the prototype object has a constructor attribute and constructor points to Type. The relationship between the constructor and the function object is a mutual reference.Two, explicit prototype and implicit prototype
1. Each function function has a prototype that is an explicit prototype attribute
2. Every instance object has an implicit prototype property
3. The value of the implicit prototype of the object is the value of the explicit prototype of its corresponding constructor
//1、每个函数function都有一个prototype,称为显式原型属性 默认指向一个空的object对象
console.log(Fn.prototype); //函数对象定义时添加此属性
//2、每个实例对象都有一个_proto_可称为隐式原型(属性)
//创建实例对象
const fn = new Fn(); // this.__proto__ = Fn.prototype
console.log(fn.__proto__); //创建对象添加此属性
//3、对象的隐式原型的值为其对应构造函数的显式原型的值
console.log(Fn.prototype === fn.__proto__);
//4、给原型添加方法
Fn.prototype.test = function(){
console.log("test()");
};
//通过实例对象调用原型的方法
fn.test();
Code prototype icon:
function Fn(){
}
var fn = new Fn();
Fn.prototype.test = function(){
console.log("test()");
};
fn.text();
Summary:
The prototype property of the function:
- Automatically added when defining the function, the default value is an empty Object object.
- _Proto_ property of the object: automatically added when the object is created, the default value is the prototype property value of the constructor.
- Explicit prototypes can be operated directly, but implicit prototypes cannot be operated directly.
Third, the prototype chain
When accessing an object property, it is now searched in its own property and returned when found.
If you don't look up the _proto_ chain again, find and return.
If not found in the end, return undefined
Alias: implicit prototype chain
Code: function Fn(){
this.test1 = function(){
console.log("test1()");
};
console.log(this);
}
Fn.prototype.test2 = function(){
console.log('test2()');
};
//创建一个实例对象
var fn = new Fn();
console.log(fn);
console.log(fn.__proto__);
Prototype chain icon:
Note: At the end of the prototype chain, the implicit prototype property of Object is null, and the prototype chain is an implicit prototype chain.
The role of the prototype chain: to find the properties of the object.
Scope chain: Find variables.
Four, summary:
1. All functions have two properties, an implicit prototype and an explicit prototype. Because all functions are instance objects of uppercase Function. The following two lines of code are equivalent
function foo(){
}
var foo = new Function();