prototype and __proto__ diagram
concept
prototype is a function attribute (Each function has a prototype property), this property is a pointer to an object. It is a prototype of an object to modify the properties.
__proto__
It is an object that has a built-in property, the internal JS use the search attribute prototype chain. Related to the environment with the browser, IE can not access
var Person = function(){};
var p = new Person();
Creating an object above, subjected to three-step
(1) var p = {} ; that is, the initialization of an object P
(2) p.__proto__= Person.prototype;
(. 3)Person.call(p)
p.__proto__ === Person.prototype //true
Remember
prototype constructor is a unique property;
Object __prototype__
prototype Properties constructor which normally correspond to each other;
All the prototype Object.prototype constructor method (except Object.prototype itself)
ES6 Class prototype property and property __proto__
Class constructor as syntactic sugar, while the prototype property and __proto__
property, so there are two simultaneous inheritance chain.
(1) sub-class __proto__
attribute indicating inheritance constructor always points to the parent class.
(2) _ subclass prototype property _proto__
attribute indicates inherited methods, always points to the parent class prototype property.
class A {
}
class B extends A {
}
B.__proto__ === A // true
B.prototype.__proto__ === A.prototype // true
B is a subclass __proto__
attribute points to the parent class A, class B prototype property of a sub- __proto__
attribute points A prototype property of the parent class.
This results because the class inheritance is implemented according to the following mode.
class A {
}
class B {
}
// B的实例继承A的实例
Object.setPrototypeOf(B.prototype, A.prototype);
// B继承A的静态属性
Object.setPrototypeOf(B, A);
"Extended object" chapter is given over to achieve Object.setPrototypeOf methods.
Object.setPrototypeOf = function (obj, proto) {
obj.__proto__ = proto;
return obj;
}
Object.setPrototypeOf(B.prototype, A.prototype);
// 等同于
B.prototype.__proto__ = A.prototype;
Object.setPrototypeOf(B, A);
// 等同于
B.__proto__ = A;
This inheritance two chains can be understood: as an object, prototype (the __proto__ properties) subclass (B) is the parent class (A); as a constructor, prototype (prototype attributes) subclass (B) is examples of the parent class.
Object.create(A.prototype);
// 等同于
B.prototype.__proto__ = A.prototype;